Skip to content

DOM Nodes

JavaScript HTML DOM: Manipulating Elements (Nodes)

Section titled “JavaScript HTML DOM: Manipulating Elements (Nodes)”

The HTML DOM (Document Object Model) represents an HTML document as a tree of nodes. JavaScript can interact with this tree to dynamically add, remove, and modify HTML elements and their content.

To add a new element to the HTML DOM, you typically create the element node first, then optionally create any content (like text nodes), and finally append it to an existing element in the document.

Basic Method: createElement, createTextNode, appendChild

Section titled “Basic Method: createElement, createTextNode, appendChild”

Let’s create a new paragraph and add it to a div:

<!-- HTML Structure -->
<div id="div1">
<p id="p1">This is an existing paragraph.</p>
</div>
<script>
// 1. Create a new <p> element
const newParagraph = document.createElement("p");
// 2. Create a text node for its content
const newText = document.createTextNode("This is a newly added paragraph.");
// 3. Append the text node to the new paragraph
newParagraph.appendChild(newText);
// 4. Find an existing element to append to
const parentDiv = document.getElementById("div1");
// 5. Append the new paragraph to the existing element
parentDiv.appendChild(newParagraph);
</script>

Explanation:

  • document.createElement("p"): Creates an empty <p> element node.
  • document.createTextNode("..."): Creates a text node. Text inside HTML elements are technically text nodes.
  • newParagraph.appendChild(newText): Adds the text node as a child of the new <p> element.
  • document.getElementById("div1"): Selects the div element where we want to add our new paragraph.
  • parentDiv.appendChild(newParagraph): Adds the newly created paragraph (with its text content) as the last child of parentDiv.

Modern JavaScript provides more convenient methods for inserting elements: append(), prepend(), before(), after().

element.append(...nodesOrDOMStrings): Appends nodes or DOM strings after the last child of element.

element.prepend(...nodesOrDOMStrings): Inserts nodes or DOM strings before the first child of element.

element.before(...nodesOrDOMStrings): Inserts nodes or DOM strings before element itself (as a sibling).

element.after(...nodesOrDOMStrings): Inserts nodes or DOM strings after element itself (as a sibling).

Example using append():

// Assuming parentDiv is already selected as in the previous example
const anotherParagraph = document.createElement("p");
anotherParagraph.textContent = "Another paragraph using append()."; // Easier way to set text
parentDiv.append(anotherParagraph, "Some text directly appended.");

Using textContent is often simpler and safer than createTextNode and appendChild for just setting text content, as it automatically handles special characters.

Inserting Before an Existing Element: insertBefore()

Section titled “Inserting Before an Existing Element: insertBefore()”

The appendChild() method (and append()) adds the new element as the last child. If you need to insert an element before a specific existing child, use parentNode.insertBefore(newNode, referenceNode).

<!-- HTML Structure -->
<div id="div2">
<p id="pRef">This is the reference paragraph.</p>
<p>Another paragraph.</p>
</div>
<script>
const yetAnotherPara = document.createElement("p");
yetAnotherPara.textContent = "Inserted before pRef.";
const parentContainer = document.getElementById("div2");
const referenceParagraph = document.getElementById("pRef");
parentContainer.insertBefore(yetAnotherPara, referenceParagraph);
</script>

If referenceNode is null, insertBefore() behaves like appendChild().

Traditional Method: parentNode.removeChild(childNode)

Section titled “Traditional Method: parentNode.removeChild(childNode)”

To remove an HTML element, you historically needed a reference to its parent node.

<!-- HTML Structure -->
<div id="div3">
<p id="pToRemove">This paragraph will be removed.</p>
<p>This paragraph will remain.</p>
</div>
<script>
const parentOfRemovable = document.getElementById("div3");
const childToRemove = document.getElementById("pToRemove");
if (parentOfRemovable && childToRemove) {
parentOfRemovable.removeChild(childToRemove);
}
</script>

A common workaround if you only have the child reference:

const childNode = document.getElementById("pToRemove");
if (childNode && childNode.parentNode) {
childNode.parentNode.removeChild(childNode);
}

Modern JavaScript provides a much simpler way: call the remove() method directly on the element you want to remove.

const elementToRemove = document.getElementById("pToRemove");
if (elementToRemove) {
elementToRemove.remove();
}

Traditional Method: parentNode.replaceChild(newNode, oldNode)

Section titled “Traditional Method: parentNode.replaceChild(newNode, oldNode)”

To replace an HTML element, you can use the replaceChild() method on its parent.

<!-- HTML Structure -->
<div id="div4">
<p id="pToReplace">This paragraph will be replaced.</p>
</div>
<script>
const newReplacementPara = document.createElement("p");
newReplacementPara.textContent = "This is the replacement paragraph.";
const parentForReplacement = document.getElementById("div4");
const oldParagraph = document.getElementById("pToReplace");
if (parentForReplacement && oldParagraph) {
parentForReplacement.replaceChild(newReplacementPara, oldParagraph);
}
</script>

Modern Method: element.replaceWith(newNodeOrDOMString)

Section titled “Modern Method: element.replaceWith(newNodeOrDOMString)”

A more modern and convenient way is to use the replaceWith() method directly on the element to be replaced.

const paragraphToReplace = document.getElementById("pToReplace");
const freshParagraph = document.createElement("p");
freshParagraph.textContent = "Replaced using replaceWith().";
if (paragraphToReplace) {
paragraphToReplace.replaceWith(freshParagraph, " And some text too!");
}

Further Learning: For complex DOM manipulations, consider using DocumentFragment to improve performance by batching operations. Also, explore how modern JavaScript frameworks (like React, Vue, Angular) abstract away direct DOM manipulation.