Table of Contents
Creating HTML Elements Dynamically with JavaScript: DOM Manipulation Techniques
Adding and Deleting Elements
| Method | Description |
|---|---|
|
Create an HTML element |
|
Remove an HTML element |
|
Add an HTML element |
|
Replace an HTML element |
|
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.