HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM Nodes

JavaScript allows you to create new elements and add them to the document, or remove existing elements. This process is known as Dynamic DOM Modification.


Creating New Nodes

To add a new element to the HTML DOM, you must create the element (the node) first, and then append it to an existing element.

// 1. Create the element
const para = document.createElement("p");

// 2. Create a text node
const node = document.createTextNode("This is new.");

// 3. Append text to element
para.appendChild(node);

// 4. Append element to the document
const element = document.getElementById("div1");
element.appendChild(para);

Inserting Before

The appendChild() method appends the new element as the last child. To insert it in a specific position, use insertBefore().

const parent = document.getElementById("div1");
const child = document.getElementById("p1");
parent.insertBefore(para, child);

Removing Nodes

Modern browsers allow you to remove an element directly using the remove() method. To support older browsers, you may need to use removeChild().

// Modern way
const elm = document.getElementById("p1");
elm.remove();

// Legacy way (Parent must remove child)
const parent = document.getElementById("div1");
const child = document.getElementById("p1");
parent.removeChild(child);

Replacing Nodes

To replace an element in the HTML DOM, use the replaceChild() method.

parent.replaceChild(para, child); // (New Node, Old Node)
Technical Detail: When you use createElement(), the element exists only in computer memory. It doesn't appear on the screen until you "anchor" it to the DOM using appendChild or insertBefore.

Key Points to Remember

  • Use createElement() to build new tags
  • Use createTextNode() for plain text content
  • appendChild() adds a node as the final child
  • insertBefore() adds a node before a specific reference
  • Nodes must be "anchored" to a parent to become visible
  • remove() is the easiest way to delete elements in modern JS
  • Lifecycle management is key for building Single Page Applications (SPAs)