How to useCreateElement in Javascript

In an HTML document, the document.createElement() is a method used to create the HTML element. The element specified using elementName is created or an unknown HTML element is created if the specified elementName is not recognized. 

Syntax:

let element = document.createElement("elementName");

Example: In this example, we will display an image using CreateElement.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <title>Display Image</title>
</head>
 
<body>
 
 
    <script>
        function show_image(src, width, height,alt) {
            // Create a new image element
            let img = document.createElement("img");
 
            // Set the source, width,
            // height, and alt attributes
            img.src = src;
            img.width = width;
            img.height = height;
            img.alt = alt;
 
            // Append the image element
            // to the body of the document
            document.body.appendChild(img);
        }
 
        // Example usage:
        show_image(
"https://media.w3wiki.org/wp-content/uploads/20231228172727/gfg-image.jpg",
            300, 200,"gfg logo");
    </script>
 
</body>
 
</html>


Output:

How to Display Images in JavaScript ?

To display images in JavaScript, we have different approaches. In this article, we are going to learn how to display images in JavaScript.

Below are the approaches to display images in JavaScript:

Table of Content

  • Using CreateElement
  • Using InnerHTML

Similar Reads

Approach 1: Using CreateElement

In an HTML document, the document.createElement() is a method used to create the HTML element. The element specified using elementName is created or an unknown HTML element is created if the specified elementName is not recognized....

Approach 2: Using InnerHTML

...

Contact Us