JavaScript Tutorial

DOM Nodes

DOM nodes are the individual elements or entities within the Document Object Model (DOM) tree. They represent various parts of an HTML or XML document, such as elements, text nodes, comments, attributes, and more. Each node in the DOM tree corresponds to a specific element or piece of content within the document.

In this topic we will learn how to Add and Remove Nodes (HTML Elements)

Adding New HTML Elements (Nodes)

To add a new element to the HTML content, the user first needs to create the element (element node), and then append it to an existing element.

Input:-

Output :-

Below is the explanation for above example:-

This code creates a new <p> element:

var para3 = document.createElement("p");

To add text to the <p> element, the user needs to create a text node first. This code creates a text node:

var node = document.createTextNode("This is new paragraph.");

Then user appends the text node to the <p> element:

para3.appendChild(node);

Finally, the user will append the new element to an existing element.

var element = document.getElementById("myDiv");

This code appends the new element to the existing element:

element.appendChild(para3);

Creating new HTML Elements - insertBefore()

The appendChild() method used in the previous example, appended the new element as the last child of the parent.

To insert before a specific node we use insertBefore() method,

Input:-

Output :-

Removing Existing HTML Elements

To remove an existing HTML element, use the remove() method:

Input:-

Output (Before Click):-

Output (After Click):-

Below is the explanation for above example:-

The HTML document contains a <div> element with two child nodes (two <p> elements):

Find the element that you want to remove:

var element= document.getElementById("para1");

Then use the remove() method to remove that element:

element.remove();

Note:- The remove() method does not work in older browsers, see the example below on how to use removeChild() instead.

Removing a Child Node

For some browsers that do not support the remove() method, you might have to find the parent node to remove an element:

Input:-

Output :-

Below is the explanation for above example:-

This HTML document contains a <div> element with two child nodes (two <p> elements):

[tryjavascript_Below is the explanation for the above example:-]

Find the element with id="myDiv":

var parent = document.getElementById("myDiv");

Find the <p> element with id="para1":

var child1 = document.getElementById("para1");

Remove the child from the parent:

parent.removeChild(child1);

Here is below a common workaround: Find the child that user want to remove, and use its parentNode property to find the parent:

var child1 = document.getElementById("para1");

child1.parentNode.removeChild(child1);

Replacing HTML Elements 

To replace an element from the HTMLelement, use the replaceChild() method:

Input:-

Output :-


Go back to Previous Course