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.
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);
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);
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);
To replace an element in the HTML DOM, use the replaceChild()
method.
parent.replaceChild(para, child); // (New Node, Old Node)
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.
createElement() to build new tagscreateTextNode() for plain text contentappendChild() adds a node as the final childinsertBefore() adds a node before a specific referenceremove() is the easiest way to delete elements in modern
JS