Creating HTML Elements Dynamically with JavaScript: DOM Manipulation Techniques
☰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
Some text
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 element var myText = document.createTextNode("text added using JS"); // Create a text node that has the text for
myParagraph.appendChild(myText); // Append the text to
document.body.appendChild(myParagraph); // Append
to
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.