JavaScript HTML DOM Elements


Adding and Deleting Nodes (HTML Elements)


Creating New HTML Elements (Nodes)

To include a new item in the HTML document, start by forming the element (known as an element node). Afterward, attach it to an already existing element.


Example Explained 

This code generates a fresh <p> element.

const para = document.createElement("p");

To insert text into the <p> element, start by making a text node. The following code demonstrates the creation of a text node:

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

Next, add the text node to the <p> element.

para.appendChild(node);

In the end, add the new element to an already existing element.

This code locates an already present element.

const element = document.getElementById("div1");

This code adds a new element to an already existing element.

element.appendChild(para);

Creating new HTML Elements - insertBefore()

In the earlier example, the appendChild() method added the new element as the last child of the parent.

If you prefer not to do that, you can utilize the insertBefore() method:


Removing Existing HTML Elements

To delete an HTML element, employ the remove() method.

Example Explained 

The HTML file has a <div> part with two subparts (two <p> elements):

<div>
  <p id="p1">This is a paragraph.</p>
  <p id="p2">This is another paragraph.</p>
</div>

Locate the item you wish to delete.

const elmnt = document.getElementById("p1");

Next, use the remove() method on the specified element.

elmnt.remove();

The remove() method doesn't function in older web browsers. Refer to the example below to understand how to utilize removeChild() instead.


Removing a Child Node

For browsers that can't use the remove() method, you need to locate the parent node to delete an element.


Example Explained 

This webpage has an <div> section, and inside it, there are two smaller parts (two <p> elements):

<div id="div1">
  <p id="p1">This is a paragraph.</p>
  <p id="p2">This is another paragraph.</p>
</div>

Locate the item with the identifier id="div1":

const parent = document.getElementById("div1");

Locate the<p> element with theid="p1":

const child = document.getElementById("p1");

Separate the child from its parent.

parent.removeChild(child);

A simple solution is to locate the child element you wish to delete and utilize its parentNode property to identify its parent.

const child = document.getElementById("p1");
child.parentNode.removeChild(child);

Replacing HTML Elements 

To swap out an element in the HTML DOM, employ the replaceChild() method.