Creating HTML Elements Dynamically with JavaScript: DOM Manipulation Techniques

Rumman Ansari   Software Engineer   2024-07-09 09:53:37   5524  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Adding and Deleting Elements

Method Description
 document.createElement(element) 
Create an HTML element
 document.removeChild(element) 
Remove an HTML element
 document.appendChild(element) 
Add an HTML element
 document.replaceChild(new, old) 
Replace an HTML element
 document.write(text) 
Write into the HTML output stream

You can create HTML elements using Javascript. Consider the following HTML code



<body>
<p>Some text</p>
</body>

Now you need to create a 

 tag inside  using Javascript. How can you do that? Take a look at the following code snippet.



var myParagraph = document.createElement("p");    // Create a <p> element
var myText = document.createTextNode("text added using JS"); 
// Create a text node that has the text for <p>
myParagraph.appendChild(myText);   // Append the text to <p>
document.body.appendChild(myParagraph); // Append <p> to <body>


You can see that Javascript makes use of three methods i.e. createElement(), createTextNode(), and apppendChild() to create a HTML element and append them in your HTML.