How to add an image in a HTML page using javascript ?


Examples of how to add an image in a HTML page using javascript:

Add an image using javascript

Let's create a variable image with createElement ("img"):

var img = document.createElement("img");

then indicate the name of the image (Note: if the image is not in the same directory as the html document, we can also specify the full path to the image for example './path_to_img/matplotlib-grid- 02.png '):

img.src = "matplotlib-grid-02.png";

and finally display the image in the html page

var block = document.getElementById("x");
block.appendChild(img);

Sample code using this image

<!DOCTYPE html>
<html lang="en">
<head>

    <title>Test Javascript</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

</head>

<body>

    <div id="x"></div>

    <script>

    var img = document.createElement("img");
    img.src = "matplotlib-grid-02.png";

    var div = document.getElementById("x");
    div.appendChild(img);
    //block.setAttribute("style", "text-align:center");

    </script>

</body>
</html>

returns

How to add an image in a HTML page using javascript ?
How to add an image in a HTML page using javascript ?

Change the style of the div element

You can then for example modify the style of the div containing the image with

div.setAttribute("style", "  ");

Code

<!DOCTYPE html>
<html lang="en">
<head>

    <title>Test Javascript</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

</head>

<body>

    <div id="x"></div>

    <script>

    var img = document.createElement("img");
    img.src = "matplotlib-grid-02.png";

    var div = document.getElementById("x");
    div.appendChild(img);
    div.setAttribute("style", "text-align:center");

    </script>

</body>
</html>

returns

How to add an image in a HTML page using javascript ?
How to add an image in a HTML page using javascript ?

Update the style of the image

You can also change the style of the image with

img.setAttribute("style", " ");

Example of code

<!DOCTYPE html>
<html lang="en">
<head>

    <title>Test Javascript</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

</head>

<body>

    <div id="x"></div>

    <script>

    var img = document.createElement("img");
    img.src = "matplotlib-grid-02.png";
    img.setAttribute("style", "margin-top: 80px;");

    var div = document.getElementById("x");
    div.appendChild(img);
    div.setAttribute("style", "text-align:center");

    </script>

</body>
</html>

returns

How to add an image in a HTML page using javascript ?
How to add an image in a HTML page using javascript ?

References

Image

of