Reading history

JavaScript DOM Traversal and Manipulation

7 min read 1 views

Move around the DOM with parentElement, children, siblings and closest(), then create, insert, replace, clone and remove elements safely and efficiently.

Once you can select an element, you often need to move around the page from it: up to its parent, across to its neighbours, down to its children. You also need to build new elements and put them in exactly the right place. This lesson covers DOM traversal, with properties such as parentElement and the very useful closest(), and DOM manipulation with append, before, replaceWith, document fragments and more.

In this lesson you will learn

  • Moving between parents, children and siblings
  • Finding the nearest matching ancestor with closest()
  • Creating elements and placing them with append, prepend, before and after
  • Replacing, copying and removing elements
  • Adding many elements efficiently, and safely

You should know the DOM basics and loops.

Moving Around the DOM Tree

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DOM traversal</title>
  <style>
    body { font-family: sans-serif; margin: 12px; font-size: 14px; }
    .class-list { border: 1px solid #ccc; padding: 6px 10px; border-radius: 6px; }
    .hit { background: #fff59d; }
    #log { font-family: monospace; font-size: 12px; white-space: pre-line; color: #37474f; }
  </style>
</head>
<body>
  <section class="class-list" id="nine">
    <h3>Class Nine</h3>
    <ul>
      <li>Arif</li>
      <li id="start">Bithi</li>
      <li>Chayan</li>
    </ul>
  </section>
  <p id="log"></p>
  <script>
    var start = document.getElementById("start");
    var lines = [];
    function note(label, el) {
      lines.push(label + ": " + (el ? el.tagName + " " + el.textContent.trim().split("\n")[0] : "null"));
    }
    note("parentElement", start.parentElement);               // the <ul>
    note("previousElementSibling", start.previousElementSibling);
    note("nextElementSibling", start.nextElementSibling);
    note("closest('section')", start.closest("section"));     // nearest matching ancestor
    note("closest('table')", start.closest("table"));         // no match: null

    var list = start.parentElement;
    lines.push("children.length: " + list.children.length);
    note("firstElementChild", list.firstElementChild);
    note("lastElementChild", list.lastElementChild);

    // querySelector also works inside one element, not just the document
    var section = start.closest("section");
    note("section.querySelector('h3')", section.querySelector("h3"));

    // Highlight every name that comes after Bithi
    var el = start.nextElementSibling;
    while (el) { el.classList.add("hit"); el = el.nextElementSibling; }

    document.getElementById("log").textContent = lines.join("\n");
  </script>
</body>
</html>

Result

  • parentElement goes one level up. children is a live collection of an element’s child elements, and firstElementChild and lastElementChild are its first and last.
  • previousElementSibling and nextElementSibling move sideways. They return null at the ends, which is why the loop while (el) stops after Chayan.
  • closest(selector) checks the element itself, then each ancestor, and returns the first that matches, or null. It is the standard way to find “the card this button belongs to”.
  • querySelector and querySelectorAll also work on any element, searching only inside it.
  • There are also parentNode, childNodes and nextSibling, but these include text nodes such as the spaces between tags. The Element versions are almost always what you want.

Creating and Placing Elements

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Building the DOM</title>
  <style>
    body { font-family: sans-serif; margin: 12px; font-size: 14px; }
    li { margin: 2px 0; }
    .new { color: #2e7d32; font-weight: bold; }
    .note { color: #6d4c41; font-style: italic; }
  </style>
</head>
<body>
  <ul id="fruits">
    <li>Mango</li>
    <li id="banana">Banana</li>
    <li id="old">Jackfruit (old entry)</li>
  </ul>
  <script>
    var list = document.getElementById("fruits");

    // 1. createElement + textContent + append: the safe, standard way
    var li = document.createElement("li");
    li.textContent = "Guava";
    li.className = "new";
    list.append(li);                         // add at the end

    // 2. prepend adds at the start; before and after place nodes next to another node
    var first = document.createElement("li");
    first.textContent = "Lychee";
    list.prepend(first);
    var star = document.createElement("li");
    star.textContent = "Star fruit";
    document.getElementById("banana").after(star);
    document.getElementById("banana").append(" (ripe today)");   // plain text is allowed too

    // 3. Add many items at once with a DocumentFragment (one page update)
    var frag = document.createDocumentFragment();
    ["Papaya", "Pineapple"].forEach(function (name) {
      var item = document.createElement("li");
      item.textContent = name;
      frag.append(item);
    });
    list.append(frag);

    // 4. replaceWith swaps an element; cloneNode copies one
    var fresh = document.createElement("li");
    fresh.textContent = "Jackfruit";
    document.getElementById("old").replaceWith(fresh);
    list.append(fresh.cloneNode(true));      // true = copy its text too

    // 5. remove() deletes an element
    list.children[1].remove();               // removes Mango, the second item

    // 6. insertAdjacentHTML parses HTML: use it only with text you wrote yourself
    list.insertAdjacentHTML("afterend", '<p class="note">' + list.children.length + " fruits listed</p>");
  </script>
</body>
</html>

Result

  • document.createElement("li") makes a new, unattached element. Set its textContent and classes, then insert it.
  • append adds inside, at the end; prepend adds inside, at the start. before and after place a node next to another one as a sibling. All four accept several nodes or plain strings at once.
  • A DocumentFragment is an invisible container. Build many elements inside it, then insert it once: the page updates one time instead of once per item.
  • replaceWith swaps an element for another. cloneNode(true) makes a copy including everything inside; cloneNode(false) copies only the element itself.
  • remove() deletes an element. Here it removes Mango, the second item.
  • insertAdjacentHTML(position, html) parses an HTML string at one of four positions: beforebegin, afterbegin, beforeend or afterend. Like innerHTML, never use it with text typed by users, because it can run injected code.

Quick Reference

GoalUse
Parent / nearest matching ancestorel.parentElement / el.closest(".card")
Childrenel.children, firstElementChild, lastElementChild
SiblingspreviousElementSibling, nextElementSibling
Insert insideappend, prepend
Insert besidebefore, after
Replace all childrenel.replaceChildren(...nodes) (no arguments empties it)
Swap / copy / deletereplaceWith, cloneNode(true), remove

Common Mistakes

  1. Using innerHTML += in a loop. It re-parses the whole list every time and destroys existing event listeners.
  2. Inserting user text as HTML instead of with textContent.
  3. Using nextSibling and getting a whitespace text node instead of the element.
  4. Forgetting that inserting moves. Appending an element that is already on the page moves it; clone it if you want a copy.

Practice Exercises

Exercise 1. Given a button inside a .product card, change the text of that card’s .price element to “Sold out”.

Show answer
button.closest(".product").querySelector(".price").textContent = "Sold out";

Exercise 2. Build a <ul> of the names in ["Asha", "Babu", "Chandni"] and add it to the end of document.body with a single insertion.

Show answer
const ul = document.createElement("ul");
for (const name of ["Asha", "Babu", "Chandni"]) {
  const li = document.createElement("li");
  li.textContent = name;
  ul.append(li);           // ul is not on the page yet, so this is cheap
}
document.body.append(ul);  // one insertion

Frequently Asked Questions

What is the difference between append and appendChild?

appendChild is older, accepts exactly one node and returns it. append accepts several nodes and plain strings and returns nothing. In modern code append is usually more convenient.

Is it slow to change the DOM many times?

Each change can make the browser recalculate the layout, so many separate changes add up. Build new content off the page or in a DocumentFragment, then insert it once.

Summary

  • Traverse with parentElement, children, the sibling properties and closest().
  • Create with createElement and fill with textContent.
  • Place with append, prepend, before, after and replaceWith.
  • Batch insertions with a fragment and never insert user text as HTML.

Next: Event Bubbling, Capturing and Delegation.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *