How to add a new element to HTML DOM in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

To add a new element to the HTML DOM, we have to create it first and then we need to append it to the existing element.

Steps to follow

1) First, create a div section and add some text to it using <p> tags

2) Create an element <p> using document.createElement("p").

3) Create a text, using document.createTextNode(), so as to insert it in the above-created element("p").

4) Using appendChild() try to append the created element, along with text, to the existing div tag.

Thus a new element is created(<p>) and appended to the existing element(<div>).

Example

In the following example, initially the div section consists of only 2 texts. But later on, one more text is created and added to the div section as shown in the output. 

Live Demo

<html>
<body>
<div id="new">
<p id="p1">Tutorix</p>
<p id="p2">Tutorialspoint</p>
</div>
<script>
   var tag = document.createElement("p");
   var text = document.createTextNode("Tutorix is the best e-learning platform");
   tag.appendChild(text);
   var element = document.getElementById("new");
   element.appendChild(tag);
</script>
</body>
</html>

Output

Tutorix

Tutorialspoint

Tutorix is the best e-learning platform
raja
Published on 19-Jul-2019 16:59:17
Advertisements