DEV Community

Sudhakar V
Sudhakar V

Posted on

HTML DOM Document 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.

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

element. Input :

<!DOCTYPE html>



<br> function createparagraph() {<br> let x = document.createElement(&quot;p&quot;);<br> let t =<br> document.createTextNode(&quot;Paragraph is created.&quot;);<br> x.appendChild(t);<br> document.body.appendChild(x);<br> }<br>



CreateParagraph



Output:

Explanation:

Start with creating an

element using document.createElement().
Create a text node using document.createTextNode().
Now, append the text to

using appendChild().
Append the

to

using appendChild().
Example 2: This example illustrates how to create a

element and append it to a

element. Input :

<!DOCTYPE html>



<br> function createparagraph() {<br> let x = document.createElement(&quot;p&quot;);<br> let t =<br> document.createTextNode(&quot;Paragraph is created.&quot;);<br> x.appendChild(t);<br> document.getElementById(&quot;divid&quot;).appendChild(x);<br> }<br>



A div element
CreateParagraph



Output:

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

Google Chrome
Edge
Firefox
Opera
Safari
REFERENCE:https://www.w3schools.com/jsref/met_document_createelement.asp

Top comments (0)