Inserting and Removing HTML using JavaScript

In our previous post learned about how to create or generate new HTML elements using JavaScript.
In this tutorial we will see how to insert an HTML to an existing webpage using JavaScript and we will also see that how we remove the HTML from webpage with the help of JavaScript.

In the last post we have learned how to add text content to an element by first creating a text node and then appending the node to the element with appendChild. We can of course use the same method to append the paragraph element itself, filled with content or not, to a parent node, for example the body or a div. This set of statements targets a div (line 1), creates a new paragraph element (line 2), creates the text to go in it (line 3), places the text into the paragraph (line 4) and then appends the paragraph element along with its text content to the targeted div (line 5).

1 var parentDiv = document.getElementById("div1");
2 var newParagraph = document.createElement("p");
3 var t = document.createTextNode("Hello world!");
4 newParagraph.appendChild(t);
5 parentDiv.appendChild(newParagraph);


When we add a node to our web page by appending it as a child to a parent, as we did in the example above, the limitation is that we have no control over where the new element lands among the parent's children. JavaScript always places it at the end. So for example, if the div in the example above already has three paragraphs, the new paragraph will become the fourth one, even if we'd like to place it in a higher position.

The solution is insertBefore.

For example, suppose you want the paragraph to be the first one in the div, rather than the last.

1 var parentDiv = document.getElementById("div1");
2 var newParagraph = document.createElement("p");
3 var t = document.createTextNode("Hello world!");
4 newParagraph.appendChild(t);
5 paragraph1 = parentDiv.firstChild;
6 parentDiv.insertBefore(newParagraph, paragraph1);


The example above selects one of the children of the parent element as the target (line 5), and tells  JavaScript to insert the new element and its text content before that element (line 6). There is no insertAfter method as such. But you can still do it. Simply insertBefore the target node's next sibling.

1 var target = parentDiv.childNodes[1];
2 parentDiv.insertBefore(newE, target.nextSibling);


By inserting the new node before the next sibling of the second child, you insert the new node after the second child.




And the OUTPUT webpage will be


How to Remove an HTML Element/Node

To remove a node, use can use removeChild but we must know must know the parent of the element:
 
1 var parentDiv = document.getElementById("div1");
2 var nodeToRemove = parentDiv.childNodes[2];
3 parentDiv.removeChild(nodeToRemove);







 Replacing HTML Elemnt using JavaScript


To replace an element to the HTML DOM, use the replaceChild() method: