How to use the HTML DOM createElement() method In JavaScript

The createElement() method of the HTML DOM can be used to create an SVG and image element dynamically and then the appendChild() method can be used to append it to an element as a child.

Syntax:

const varName = document.createElement(nameOfElementToBeCreated);

Example: The below code example will explain the use of the createElement() method to create an SVG image using JavaScript.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        How to make an SVG image
        using JavaScript?
    </title>
    <style>
        .container{
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 style="color: green;">
            w3wiki
        </h2>
        <h3>
            The below svg image is created dynamically
            using JavaScript.
        </h3>
    </div>
 
    <script>
        const container =
            document.querySelector('.container');
        const svg =
            document.createElementNS
            ('http://www.w3.org/2000/svg', 'svg');
        const image =
            document.createElementNS
            ('http://www.w3.org/2000/svg', 'image');
        svg.setAttribute('height', '200');
        svg.setAttribute('width', '200');
        image.setAttribute
            ('href',
"https://media.w3wiki.org/wp-content/uploads/20231004184219/gfglogo0.jpg");
        image.setAttribute('height', '200');
        image.setAttribute('width', '200');
        svg.appendChild(image);
        container.appendChild(svg);
    </script>
</body>
</html>


Output:

How to Make an SVG Image in JavaScript ?

The SVG images are vector images that do not lose their quality either in the case of Zoom in or Zoom out. These are the Scalable Vector Graphics that can be directly created using the <svg> tag in HTML or dynamically using JavaScript. Let us create an SVG using JavaScript.

We can use the below methods to create SVG images dynamically using JavaScript:

Table of Content

  • Using the HTML DOM createElement() method
  • Using the d3.js

Similar Reads

Using the HTML DOM createElement() method

The createElement() method of the HTML DOM can be used to create an SVG and image element dynamically and then the appendChild() method can be used to append it to an element as a child....

Using the d3.js

...

Contact Us