HTML | DOM createElement() Method

In 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

var 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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:
Initially:

After pressing Create Paragraph button:

Explanation:

  • Start with creating a <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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <script>
        function createparagraph() {
            var x = document.createElement("p");
            var 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>

chevron_right



Output:

Initially:

After pressing the CreateParagraph button:

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

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • SAfari


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.