How to create HTML element using JavaScript

The basic blocks of HTML are the HTML elements like,

<p>Paragraph</p>
<h1>Importtant Heading</h1>
<ul>
    <li>List item</li>
</ul>

Mostly, designing a static web page doesn’t require JavaScript. But when a dynamic web page is a need, JavaScript is the preferred option. JavaScript provides several methods that can make a web page more interactive. Often it is needed to insert an element when an event occurs. JavaScript has a method called createElement(tagname) that can create an element specified in the argument tagname. If the tagname cannot be recognized, it will return a HTMLUnknownElement. As a result of creating a new element, a new node will be added to the document tree. The createElement method of the DOM has the signature,

Element document.createElement(tagname,[options])

where the argument tagname is the name of the element that has to be created and returned.  The optional argument options  will contain the ElementCreationOptionsobject and it will be used when a custom element is defined. For instance, consider the HTML code,

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <button onclick="addElement()">CLICK ME</button>
        <script>
            function addElement() {
                let element = document.createElement('div')
                element.innerHTML = "<p>My parent tag is created with createElement method</p>"
                document.body.appendChild(element)
            }
        </script>
    </body>
</html>

Rendering the above HTML will display a button that upon clicking adds an div element to the document. If the below statements are executed in a browser console, it can be found that the element created is of type object

>let a = document.createElement('p')
>typeof a
>"object"

Also, all the other HTML elements can be created with the method createElement().

Notice the div tag after the script tag.

Leave a Reply

Your email address will not be published.