Add image to a div in JavaScript

Add image element to a div using JavaScript

Posted by Ervin Adams on August 3, 2022

Add image to a div in JavaScript

Add image element to a div using JavaScript

Posted by Ervin Adams on August 3, 2022

There are a few ways you can use to add an image to a div using JavaScript.

Here is the html with the div that you will attach the image:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 set image to div using JavaScript</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">
</head>
<body>
  <main>
    <!--Main layout-->
    <div class="container">
        <div id="img-div"></div>
    </div>
  </main>
</body>
</html>

Here are some JS examples:

Use innerHTML method

Step 1. Get the specified div elements using document.getElementById()

Step 2. Use the innerHTML method to attach image

const imgDiv = document.getElementById('img-div');
imgDiv.innerHTML = '<img width="100" height="100" src="https://picsum.photos/400">';

Use createElement() method with style object

Step 1. Get the specified div elements using document.getElementById()

Step 2. Use createElement() to create image element

Step 3. Use style object to create styling on image

Step 4. Use the append() method to attach image

const imgDiv = document.getElementById('img-div');

const image = document.createElement('img');
image.src="https://picsum.photos/100";
image.alt = "photo";
image.style.height = '400px';
image.style.width = '400px';
imgDiv.append(image);

or with setAttribute()

const imgDiv = document.getElementById('img-div');

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

 

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