How to Create an Image Element Dynamically using JavaScript?

To create an image element dynamically using JavaScript, we can use various approaches based on our use case. We will explore three effective methods in this article with complete examples and step-by-step explanations.

Approaches to Create an Image Element

Here are the three main approaches to create an image element dynamically using JavaScript:

Using createElement() Method

The createElement() method is the most standard way to create DOM elements dynamically. This approach creates a proper DOM element with full control over its properties.

How It Works

  • Use createElement('img') to create an image element
  • Set properties like src, alt, and width
  • Use appendChild() to add it to the DOM

Example

<!DOCTYPE html>
<html>
<head>
    <title>Creating Image with createElement()</title>
</head>
<body>
    <h2>Creating an Image Element Using createElement()</h2>
    <button onclick="createImage()">Create Image</button>
    <div id="imageContainer"></div>
    
    <script>
        function createImage() {
            // Get the container element
            let container = document.getElementById('imageContainer');
            
            // Create the image element
            let newImg = document.createElement('img');
            newImg.src = '/static/images/logo.png';
            newImg.alt = 'TutorialsPoint Logo';
            newImg.style.width = '200px';
            newImg.style.height = 'auto';
            
            // Append to container
            container.appendChild(newImg);
        }
    </script>
</body>
</html>

Using Image() Constructor

The Image() constructor creates an HTMLImageElement object directly. This method is particularly useful when you need to preload images or work with image objects before adding them to the DOM.

How It Works

  • Create a new image instance using new Image()
  • Set the src property to load the image
  • Optionally handle onload events
  • Add to DOM using appendChild()

Example

<!DOCTYPE html>
<html>
<head>
    <title>Creating Image with Image() Constructor</title>
</head>
<body>
    <h2>Creating an Image Element Using Image() Constructor</h2>
    <button onclick="createImage()">Create Image</button>
    <div id="imageContainer"></div>
    
    <script>
        function createImage() {
            let container = document.getElementById('imageContainer');
            
            // Create image using Image() constructor
            let newImg = new Image();
            newImg.src = '/static/images/logo.png';
            newImg.alt = 'TutorialsPoint Logo';
            newImg.style.maxWidth = '200px';
            
            // Optional: Handle image load event
            newImg.onload = function() {
                console.log('Image loaded successfully');
            };
            
            // Add to DOM
            container.appendChild(newImg);
        }
    </script>
</body>
</html>

Using innerHTML Property

The innerHTML property allows you to insert HTML as a string. While simple, this method has limitations regarding event handling and performance.

How It Works

  • Target a container element
  • Set or append HTML string using innerHTML
  • The browser parses the string and creates DOM elements

Example

<!DOCTYPE html>
<html>
<head>
    <title>Creating Image with innerHTML</title>
</head>
<body>
    <h2>Creating an Image Element Using innerHTML</h2>
    <button onclick="createImage()">Create Image</button>
    <div id="imageContainer"></div>
    
    <script>
        function createImage() {
            let container = document.getElementById('imageContainer');
            
            // Create image using innerHTML
            container.innerHTML += `
                <img src="/static/images/logo.png" 
                     alt="TutorialsPoint Logo" 
                     style="max-width: 200px; height: auto;">
            `;
        }
    </script>
</body>
</html>

Comparison of Methods

Method Performance Event Handling Best Use Case
createElement() Best Full control Production code, complex interactions
Image() Constructor Good Good Image preloading, canvas operations
innerHTML Slower Limited Simple HTML insertion

Key Points

  • createElement() is the recommended approach for production code
  • Image() constructor is ideal for preloading and image manipulation
  • innerHTML is simple but should be avoided for dynamic content with events
  • Always set the alt attribute for accessibility
  • Consider image loading events when necessary

Conclusion

For creating image elements dynamically, use createElement() for most scenarios as it provides the best performance and control. The Image() constructor is excellent for preloading, while innerHTML works for simple static content insertion.

Updated on: 2026-03-15T23:19:01+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements