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,beforeandafter - 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
parentElementgoes one level up.childrenis a live collection of an element’s child elements, andfirstElementChildandlastElementChildare its first and last.previousElementSiblingandnextElementSiblingmove sideways. They returnnullat the ends, which is why the loopwhile (el)stops after Chayan.closest(selector)checks the element itself, then each ancestor, and returns the first that matches, ornull. It is the standard way to find “the card this button belongs to”.querySelectorandquerySelectorAllalso work on any element, searching only inside it.- There are also
parentNode,childNodesandnextSibling, but these include text nodes such as the spaces between tags. TheElementversions 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 itstextContentand classes, then insert it.appendadds inside, at the end;prependadds inside, at the start.beforeandafterplace a node next to another one as a sibling. All four accept several nodes or plain strings at once.- A
DocumentFragmentis an invisible container. Build many elements inside it, then insert it once: the page updates one time instead of once per item. replaceWithswaps 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,beforeendorafterend. LikeinnerHTML, never use it with text typed by users, because it can run injected code.
Quick Reference
| Goal | Use |
|---|---|
| Parent / nearest matching ancestor | el.parentElement / el.closest(".card") |
| Children | el.children, firstElementChild, lastElementChild |
| Siblings | previousElementSibling, nextElementSibling |
| Insert inside | append, prepend |
| Insert beside | before, after |
| Replace all children | el.replaceChildren(...nodes) (no arguments empties it) |
| Swap / copy / delete | replaceWith, cloneNode(true), remove |
Common Mistakes
- Using
innerHTML +=in a loop. It re-parses the whole list every time and destroys existing event listeners. - Inserting user text as HTML instead of with
textContent. - Using
nextSiblingand getting a whitespace text node instead of the element. - 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 andclosest(). - Create with
createElementand fill withtextContent. - Place with
append,prepend,before,afterandreplaceWith. - Batch insertions with a fragment and never insert user text as HTML.
