Open In App
Related Articles

HTML DOM createElement() Method

Improve Article
Improve
Save Article
Save
Like Article
Like

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");

In the above syntax, elementName is passed as a parameter. elementName specifies the type of the created element. The nodeName of the created element is initialized to the elementName value. The document.createElement() returns the newly created element. 

Example 1: This example illustrates how to create a <p> element. Input : 

HTML




<!DOCTYPE html>
<html>
<head>
    <script>
        function createparagraph() {
            let x = document.createElement("p");
            let t =
                document.createTextNode("Paragraph is created.");
            x.appendChild(t);
            document.body.appendChild(x);
        }
    </script>
</head>
 
<body>
    <button onclick="createparagraph()">CreateParagraph</button>
</body>
</html>


Output: 

 

Explanation:

  • Start with creating an <p> element using document.createElement().
  • Create a text node using document.createTextNode().
  • Now, append the text to <p> using appendChild().
  • Append the <p> to <body> using appendChild().

Example 2: This example illustrates how to create a <p> element and append it to a <div> element. Input : 

HTML




<!DOCTYPE html>
<html>
<head>
    <script>
        function createparagraph() {
            let x = document.createElement("p");
            let t =
                document.createTextNode("Paragraph is created.");
            x.appendChild(t);
            document.getElementById("divid").appendChild(x);
        }
    </script>
</head>
<body>
    <div id="divid"> A div element</div>
    <button onclick="createparagraph()">CreateParagraph</button>
</body>
</html>


Output: 

 

Supported Browser: The browsers supported by DOM createElement() Method are listed below:

  • Google Chrome 1
  • Edge12
  • Internet Explorer 5
  • Firefox 1
  • Opera 6
  • Safari 1

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 12 Jun, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials