Open In App

How to Create an Image Element using JavaScript?

Last Updated : 24 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating an image element dynamically using JavaScript is a useful technique when you want to add images to a webpage without having to manually write the <img> tag in your HTML. This allows for more flexibility, as we can create and manipulate images based on user interactions or other conditions.

Approach to Create an Image Element in JavaScript

  • Create the Image Element: Use document.createElement('img') to create an empty <img> tag.
  • Set the Image Source (src): Assign the image URL to the src attribute.
  • Set the Alternative Text (alt): Set a description of the image for accessibility using the alt attribute.
  • Set the Title Attribute: Add a title attribute for a tooltip when the user hovers over the image.
  • Append the Image to the Document: Insert the image element into the document by appending it to a container (like body or any other element).

Now let's understand this with the help of example:

html
<html>
<head></head>
<body id="body" style="text-align:center;">

    <h1 style="color:green;">
        GeeksforGeeks
    </h1>

    <h3>
        Click on the button to add image element
    </h3>
    <button onclick="GFG_Fun()">
        click here
    </button>
    <h2 id="result" style="color:green;"></h2>
    <script>
        let res = document.getElementById('result');

        function GFG_Fun() {
            let img = document.createElement('img');
            img.src =
'https://media.geeksforgeeks.org/wp-content/uploads/20190529122828/bs21.png';
            document.getElementById('body').appendChild(img);
            res.innerHTML = "Image Element Added.";
        }
    </script>
</body>
</html>

Output:

In this example

  • A button is created to trigger a function when clicked.
  • The function creates an image element.
  • Sets its src to a specific URL.
  • Adds the image to the page and displays a message: "Image Element Added.

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

Conclusion

Creating an image element dynamically using JavaScript offers flexibility by allowing images to be added to a webpage without manually writing the <img> tag. This technique is particularly useful when images need to be added or manipulated based on user actions or other conditions.


Next Article

Similar Reads