Add image to a div in Jquery

Add image element to a div using Jquery

Posted by Luke Beeno on August 3, 2022

Add image to a div in Jquery

Add image element to a div using Jquery

Posted by Luke Beeno on August 3, 2022

Here is how you can append image to div using Jquery.

Step 1. Get the specified div field by using $("#id")

Step 2. Use createElement() to create image element or use image selector

Step 3. Use append() or appendTo() to attach image to div

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 set image to div using Jquery</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
  <main>
    <!--Main layout-->
    <div class="container">
        <div id="img-div"></div>
    </div>
  </main>
</body>
</html>

JS

Use createElement()

const image = document.createElement('img');
image.setAttribute("src", "https://picsum.photos/150");
image.setAttribute("height", "400");
image.setAttribute("width", "400");
image.setAttribute("alt", "photo");
$( "#img-div" ).append(image);

Or

Use selector

$("<img src='https://picsum.photos/150' width='400' height='400' alt='photo'/>").appendTo("#img-div");

 

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question