DOM Traversal, Collections and Animation
By Syncfusion®, Inc. · Last updated
Stepping between parent, child and sibling elements, working with HTMLCollection and NodeList, live and static collections, and moving, showing, hiding and fading elements.
What Are Traversal, Collections and Animation?
- Traversal = moving from one element to its parent, children or siblings, without searching the whole page.
- Collection = a list-like group of elements (
HTMLCollectionorNodeList). It is not a real array. - Animation = a style changed a little on each frame, so it looks smooth.
Simple lesson: every element knows its family, and small changes over time look like movement.
A Real-World Example
In a cart, each item has a Remove button.
The button uses closest(".cart-item") to find its own row, then removes it; no ids needed.
The new total flashes yellow with animate() so the customer sees it change.
ul (parent)
Rice Milk (me) Bread previousElementSibling parentElement ↑ nextElementSibling
From "me", step up to the parent or sideways to the siblings.
Each box is a small live page. Click the rendered elements after the script runs; the animations stop after a fixed number of frames.
What You Will Learn
- Parent, child and sibling navigation, and walking the tree.
- Nodes versus elements, and finding nearby elements with
closest(). HTMLCollectionandNodeList, live versus static.- Looping, reading by position, and converting to an array.
- Animating, moving, showing and hiding elements, and effects.
Navigation
The page is a tree with <html> at the top.
- Parent: the element directly above.
- Child: an element directly inside.
- Siblings: elements with the same parent.
Parent, child and sibling navigation
From the Milk item, every part of the list is one step away.
Start from the middle item and look around
<ul id="shopping">
<li>Rice</li>
<li id="milk">Milk</li>
<li>Bread</li>
</ul>
<script>
const milk = document.querySelector("#milk");
console.log("I am: ", milk.textContent);
console.log("My parent: ", milk.parentElement.id);
console.log("Sibling before: ", milk.previousElementSibling.textContent);
console.log("Sibling after: ", milk.nextElementSibling.textContent);
console.log("Parent's children:", milk.parentElement.children.length);
</script>
Expected output:
I am: Milk
My parent: shopping
Sibling before: Rice
Sibling after: Bread
Parent's children: 3
Traversing the DOM tree
Follow the links for many steps. Climbing up with parentElement stops at null after <html>:
Climb from a price label all the way to the top
<main>
<section class="product">
<div class="details">
<span id="price">₹499</span>
</div>
</section>
</main>
<script>
let current = document.querySelector("#price");
const path = [];
while (current) {
path.push(current.tagName.toLowerCase());
current = current.parentElement;
}
console.log(path.join(" → "));
</script>
Expected output:
span → div → section → main → body → html
Going down: a function that prints an element, then calls itself for each child, shows the tree's shape.
Walk down through a menu and print its outline
<nav id="menu">
<ul>
<li>Home</li>
<li>Shop
<ul>
<li>Mugs</li>
<li>Plates</li>
</ul>
</li>
</ul>
</nav>
<script>
function printOutline(element, depth) {
const label = element.tagName.toLowerCase();
const text = element.firstChild?.nodeValue?.trim() ?? "";
console.log(" ".repeat(depth) + label + (text ? " " + text : ""));
for (const child of element.children) {
printOutline(child, depth + 1);
}
}
printOutline(document.querySelector("#menu"), 0);
</script>
Expected output:
nav
ul
li Home
li Shop
ul
li Mugs
li Plates
Moving between nodes
Node = anything in the tree, including text, even the spaces between tags. Element = a tag. nextSibling/childNodes include text nodes; nextElementSibling/children skip them.
The gap between two list items is a node too
<ul id="shopping">
<li id="rice">Rice</li>
<li>Milk</li>
</ul>
<script>
const rice = document.querySelector("#rice");
const list = document.querySelector("#shopping");
console.log("nextSibling: ", rice.nextSibling);
console.log("nextElementSibling:", rice.nextElementSibling.textContent);
console.log("childNodes:", list.childNodes.length, "| children:", list.children.length);
</script>
Expected output:
nextSibling: #text "\n "
nextElementSibling: Milk
childNodes: 5 | children: 2
Prefer parentElement, children, firstElementChild, lastElementChild, nextElementSibling, previousElementSibling. The shorter names include invisible whitespace text nodes.
Finding nearby elements
Step up with closest(selector) to the nearest matching ancestor, then search down with querySelector() inside it.
From a Remove button, find its product name and price
<div class="cart-item">
<span class="name">Ceramic mug</span>
<span class="price">₹499</span>
<button type="button" class="remove">Remove</button>
</div>
<div class="cart-item">
<span class="name">Tea towel</span>
<span class="price">₹199</span>
<button type="button" class="remove">Remove</button>
</div>
<script>
for (const button of document.querySelectorAll(".remove")) {
button.addEventListener("click", () => {
const item = button.closest(".cart-item");
const name = item.querySelector(".name").textContent;
const price = item.querySelector(".price").textContent;
console.log(`Removing ${name} (${price})`);
item.remove();
});
}
document.querySelectorAll(".remove")[1].click();
console.log("Items left:", document.querySelectorAll(".cart-item").length);
</script>
Expected output:
Removing Tea towel (₹199)
Items left: 1
parentElement
The element directly above. Here a ticked checkbox colours its row.
Highlight the row that holds a ticked checkbox
<p class="task"><input type="checkbox" id="pay"> Pay the rent</p>
<script>
const pay = document.querySelector("#pay");
pay.addEventListener("change", () => {
pay.parentElement.style.background = pay.checked ? "#dcfce7" : "";
console.log("Row background:", pay.parentElement.style.background || "(none)");
});
pay.click();
pay.click();
</script>
Expected output:
Row background: rgb(220, 252, 231)
Row background: (none)
children
Every element directly inside, in order (no text nodes). Count with length; loop with for...of.
Count and list the songs in a playlist
<ol id="playlist">
<li>Morning Raga</li>
<li>Monsoon Song</li>
<li>Evening Walk</li>
</ol>
<script>
const playlist = document.querySelector("#playlist");
console.log("Songs:", playlist.children.length);
for (const song of playlist.children) {
console.log("-", song.textContent);
}
</script>
Expected output:
Songs: 3
- Morning Raga
- Monsoon Song
- Evening Walk
firstElementChild
The first element inside, or null when empty.
Crown the player at the top of the leaderboard
<ol id="leaderboard">
<li>Asha - 920 points</li>
<li>Ravi - 870 points</li>
<li>Meena - 805 points</li>
</ol>
<ul id="empty"></ul>
<script>
const leader = document.querySelector("#leaderboard").firstElementChild;
leader.textContent = "👑 " + leader.textContent;
console.log("Leader:", leader.textContent);
console.log("First child of an empty list:", document.querySelector("#empty").firstElementChild);
</script>
Expected output:
Leader: 👑 Asha - 920 points
First child of an empty list: null
lastElementChild
The last element inside: always the newest message in a chat.
Read the newest message in a chat
<div id="chat">
<p>Asha: Are you coming?</p>
<p>Ravi: Leaving now.</p>
</div>
<script>
const chat = document.querySelector("#chat");
console.log("Newest:", chat.lastElementChild.textContent);
const reply = document.createElement("p");
reply.textContent = "Asha: See you soon!";
chat.append(reply);
console.log("Newest:", chat.lastElementChild.textContent);
</script>
Expected output:
Newest: Ravi: Leaving now.
Newest: Asha: See you soon!
nextElementSibling
The element straight after, or null. A question can open the answer below it, no ids needed.
Clicking a question shows the answer right below it
<div id="faq">
<h4 class="question">Do you deliver to Pune?</h4>
<p hidden>Yes, in 2 to 3 days.</p>
<h4 class="question">Can I return a mug?</h4>
<p hidden>Yes, within 30 days.</p>
</div>
<script>
for (const question of document.querySelectorAll(".question")) {
question.addEventListener("click", () => {
const answer = question.nextElementSibling;
answer.hidden = !answer.hidden;
console.log(question.textContent, "→", answer.hidden ? "hidden" : answer.textContent);
});
}
document.querySelectorAll(".question")[1].click();
</script>
Expected output:
Can I return a mug? → Yes, within 30 days.
previousElementSibling
The element straight before, or null at the top. Great for "move up" buttons.
Move a task up the list, until it reaches the top
<ol id="tasks">
<li>Buy flowers</li>
<li>Book a table</li>
<li id="cake">Order the cake</li>
</ol>
<button type="button" id="up">Move cake up</button>
<script>
const cake = document.querySelector("#cake");
const list = document.querySelector("#tasks");
document.querySelector("#up").addEventListener("click", () => {
const above = cake.previousElementSibling;
if (!above) {
console.log("Already at the top.");
return;
}
list.insertBefore(cake, above);
console.log([...list.children].map((task) => task.textContent).join(" | "));
});
const up = document.querySelector("#up");
up.click();
up.click();
up.click();
</script>
Expected output:
Buy flowers | Order the cake | Book a table
Order the cake | Buy flowers | Book a table
Already at the top.
Any of these can be null: at the edges of a list or in an empty element. Check before reading from the result.
Collections
Collections have length and numbered positions, but are not arrays.
HTMLCollection
Elements only. From children and getElementsBy...(). No forEach().
What an HTMLCollection is, and what it can do
<ul id="menu">
<li class="dish">Masala dosa</li>
<li class="dish">Idli</li>
<li class="dish">Vada</li>
</ul>
<script>
const dishes = document.getElementsByClassName("dish");
console.log("Kind:", dishes.constructor.name);
console.log("Length:", dishes.length);
console.log("Is it an array?", Array.isArray(dishes));
console.log("Has forEach?", typeof dishes.forEach);
</script>
Expected output:
Kind: HTMLCollection
Length: 3
Is it an array? false
Has forEach? undefined
NodeList
Any nodes. From querySelectorAll() and childNodes. Has forEach(), but no map() or filter().
What a NodeList is, and what it can do
<ul id="menu">
<li class="dish">Masala dosa</li>
<li class="dish">Idli</li>
<li class="dish">Vada</li>
</ul>
<script>
const dishes = document.querySelectorAll(".dish");
console.log("Kind:", dishes.constructor.name);
console.log("Length:", dishes.length);
console.log("Is it an array?", Array.isArray(dishes));
console.log("Has forEach?", typeof dishes.forEach);
console.log("Has map?", typeof dishes.map);
</script>
Expected output:
Kind: NodeList
Length: 3
Is it an array? false
Has forEach? function
Has map? undefined
HTMLCollection | NodeList | |
|---|---|---|
| Comes from | children, getElementsBy...() | querySelectorAll(), childNodes |
| Holds | elements only | any nodes |
forEach() | no | yes |
| Updates by itself | always | only from childNodes |
Live collection vs static collection
Live = updates itself when the page changes. Static = a snapshot that never changes.
Add a dish, and see which collection notices
<ul id="menu">
<li class="dish">Masala dosa</li>
<li class="dish">Idli</li>
</ul>
<script>
const live = document.getElementsByClassName("dish");
const snapshot = document.querySelectorAll(".dish");
console.log("Before - live:", live.length, "| static:", snapshot.length);
const vada = document.createElement("li");
vada.className = "dish";
vada.textContent = "Vada";
document.querySelector("#menu").append(vada);
console.log("After - live:", live.length, "| static:", snapshot.length);
</script>
Expected output:
Before - live: 2 | static: 2
After - live: 3 | static: 2
A loop that changes the page can trip over a live collection:
Clearing a live collection while looping over it skips items
<ul>
<li class="unread">Offer: 10% off</li>
<li class="unread">Your order has shipped</li>
<li class="unread">New review</li>
<li class="unread">Password changed</li>
</ul>
<script>
const unread = document.getElementsByClassName("unread");
for (let i = 0; i < unread.length; i += 1) {
unread[i].classList.remove("unread");
}
console.log("Still unread:", unread.length);
console.log([...document.querySelectorAll(".unread")].map((item) => item.textContent));
</script>
Expected output:
Still unread: 2
[
"Your order has shipped",
"Password changed"
]
When a loop changes what a collection matches, loop over a static list: querySelectorAll() or [...collection].
Iterating over collections
for...of works on both kinds.
for...of works on an HTMLCollection and on a NodeList
<ul id="basket">
<li data-price="120">Bananas</li>
<li data-price="80">Onions</li>
<li data-price="45">Coriander</li>
</ul>
<script>
let total = 0;
for (const item of document.querySelector("#basket").children) {
total += Number(item.dataset.price);
}
console.log("Total from children:", total);
let count = 0;
for (const item of document.querySelectorAll("#basket li")) {
count += 1;
}
console.log("Items from querySelectorAll:", count);
</script>
Expected output:
Total from children: 245
Items from querySelectorAll: 3
Accessing items
Positions start at 0; the last is length - 1. A missing position: undefined with [ ], null with item().
Read items by position, including one that is not there
<ul id="queue">
<li>Asha</li>
<li>Ravi</li>
<li>Meena</li>
</ul>
<script>
const people = document.querySelectorAll("#queue li");
console.log("First:", people[0].textContent);
console.log("Last: ", people[people.length - 1].textContent);
console.log("item(1):", people.item(1).textContent);
console.log("people[10]:", people[10]);
console.log("people.item(10):", people.item(10));
</script>
Expected output:
First: Asha
Last: Meena
item(1): Ravi
people[10]: undefined
people.item(10): null
Looping through NodeList
forEach() (node and position), for...of (node), or a counting for loop when you need the position to change steps.
Three loops that number the same list of steps
<ol id="recipe">
<li>Boil water</li>
<li>Add tea leaves</li>
<li>Pour and serve</li>
</ol>
<script>
const steps = document.querySelectorAll("#recipe li");
steps.forEach((step, index) => {
console.log(`forEach ${index + 1}: ${step.textContent}`);
});
for (const step of steps) {
step.style.fontWeight = "bold";
}
console.log("for...of made", steps.length, "steps bold");
for (let i = 0; i < steps.length; i += 1) {
steps[i].title = `Step ${i + 1} of ${steps.length}`;
}
console.log("Last step's title:", steps[2].title);
</script>
Expected output:
forEach 1: Boil water
forEach 2: Add tea leaves
forEach 3: Pour and serve
for...of made 3 steps bold
Last step's title: Step 3 of 3
Converting NodeList to Array
[...list] or Array.from(list) makes a real array, so map, filter and reduce work.
Turn a NodeList into an array to filter and total the prices
<ul id="products">
<li data-price="499" data-stock="4">Ceramic mug</li>
<li data-price="199" data-stock="0">Tea towel</li>
<li data-price="899" data-stock="2">Teapot</li>
</ul>
<script>
const items = document.querySelectorAll("#products li");
try {
items.map((item) => item.textContent);
} catch (error) {
console.log("NodeList.map:", error.message);
}
const inStock = [...items].filter((item) => Number(item.dataset.stock) > 0);
console.log("In stock:", inStock.map((item) => item.textContent));
const total = Array.from(items).reduce((sum, item) => sum + Number(item.dataset.price), 0);
console.log("Total price:", total);
</script>
Expected output:
NodeList.map: items.map is not a function
In stock: [
"Ceramic mug",
"Teapot"
]
Total price: 1597
Animation
Animation adds time to style changes: change a little, wait for the next frame, change again.
Animating HTML elements
Frame = one redraw of the screen. requestAnimationFrame(fn) calls fn right before the next one.
Fill a progress bar in 10 frames
<div style="width: 240px; border: 1px solid #c9c2b6;">
<div id="bar" style="height: 14px; width: 0%; background: #16a34a;"></div>
</div>
<p id="label">0%</p>
<script>
const bar = document.querySelector("#bar");
const label = document.querySelector("#label");
const totalFrames = 10;
let frame = 0;
function drawFrame() {
frame += 1;
const percent = frame * 10;
bar.style.width = percent + "%";
label.textContent = percent + "%";
if (frame < totalFrames) {
requestAnimationFrame(drawFrame);
} else {
console.log("Finished after", frame, "frames at", bar.style.width);
}
}
requestAnimationFrame(drawFrame);
console.log("Animation started. Width now:", bar.style.width);
</script>
Expected output:
Animation started. Width now: 0%
Finished after 10 frames at 100%
Why the name? It requests a call before the next animation frame.
Always decide how an animation ends. Without a stopping rule, it keeps the browser busy forever.
Moving elements
Change transform: translateX(...) a little each frame: distance ÷ frames per step.
Slide a delivery van 200 pixels in 20 frames
<div style="width: 260px; border-bottom: 2px solid #c9c2b6;">
<div id="van" style="display: inline-block; font-size: 28px;">🚚</div>
</div>
<button type="button" id="drive">Drive again</button>
<script>
const van = document.querySelector("#van");
const distance = 200;
const totalFrames = 20;
function drive() {
let frame = 0;
function step() {
frame += 1;
const x = (distance / totalFrames) * frame;
van.style.transform = `translateX(${x}px)`;
if (frame < totalFrames) {
requestAnimationFrame(step);
} else {
console.log("Arrived:", van.style.transform);
}
}
van.style.transform = "translateX(0px)";
requestAnimationFrame(step);
}
document.querySelector("#drive").addEventListener("click", drive);
drive();
console.log("Setting off from:", van.style.transform);
</script>
Expected output:
Setting off from: translateX(0px)
Arrived: translateX(200px)
Showing and hiding elements
el.hidden = true hides; false shows. !details.hidden flips it.
Toggle a delivery-details panel
<button type="button" id="toggle">Show delivery details</button>
<div id="details" hidden>
<p>Arrives on Friday. Free for orders over ₹999.</p>
</div>
<script>
const toggle = document.querySelector("#toggle");
const details = document.querySelector("#details");
toggle.addEventListener("click", () => {
details.hidden = !details.hidden;
toggle.textContent = details.hidden ? "Show delivery details" : "Hide delivery details";
console.log("hidden:", details.hidden, "| button says:", toggle.textContent);
});
toggle.click();
toggle.click();
</script>
Expected output:
hidden: false | button says: Hide delivery details
hidden: true | button says: Show delivery details
Also: style.display = "none", or a class whose CSS hides it. getComputedStyle() shows what really applied.
Three ways to hide, and one way to check
<style>.is-hidden { display: none; }</style>
<p id="a">Hidden with the hidden property</p>
<p id="b">Hidden with style.display</p>
<p id="c">Hidden with a class</p>
<script>
const a = document.querySelector("#a");
const b = document.querySelector("#b");
const c = document.querySelector("#c");
a.hidden = true;
b.style.display = "none";
c.classList.add("is-hidden");
for (const element of [a, b, c]) {
console.log(element.id, "display is", getComputedStyle(element).display);
}
c.classList.toggle("is-hidden");
console.log("c after toggle:", getComputedStyle(c).display);
</script>
Expected output:
a display is none
b display is none
c display is none
c after toggle: block
Basic DOM effects
el.animate(keyframes, { duration }) lets the browser animate between styles: fade-ins, flashes.
Fade in a saved message, then flash the updated total
<p id="saved" style="opacity: 0;">✔ Your address was saved.</p>
<p>Total: <span id="total">₹499</span></p>
<button type="button" id="replay">Play again</button>
<script>
const saved = document.querySelector("#saved");
const total = document.querySelector("#total");
function playEffects() {
const fade = saved.animate(
[{ opacity: 0 }, { opacity: 1 }],
{ duration: 600, fill: "forwards" }
);
total.textContent = "₹698";
const flash = total.animate(
[{ backgroundColor: "#fde047" }, { backgroundColor: "transparent" }],
{ duration: 800 }
);
Promise.all([fade.finished, flash.finished]).then(() => {
console.log("Both effects finished:", fade.playState, flash.playState);
});
}
document.querySelector("#replay").addEventListener("click", playEffects);
playEffects();
console.log("Effects started. New total:", total.textContent);
</script>
Expected output:
Effects started. New total: ₹698
Both effects finished: finished finished
Some people set "reduce motion". Check matchMedia("(prefers-reduced-motion: reduce)").matches and skip or shorten effects.
Traversal in the Editor
Each Remove button finds its own row with closest(), the total is recalculated from a static list, and the total flashes with animate().
Remove buttons that find their own row
const items = [["Notebook", 60], ["Steel bottle", 299], ["Pencil box", 120]];
const cart = document.querySelector("#cart");
const total = document.querySelector("#total");
for (const [name, price] of items) {
const li = document.createElement("li");
li.className = "cart-item";
li.dataset.price = price;
li.innerHTML = `<span class="name">${name}</span> ₹${price} <button class="remove">Remove</button>`;
cart.append(li);
}
function updateTotal() {
const prices = [...cart.querySelectorAll(".cart-item")].map((li) => Number(li.dataset.price));
total.textContent = `₹${prices.reduce((sum, p) => sum + p, 0)}`;
// ?.() skips the flash in places with no animate(), such as old browsers.
total.animate?.([{ background: "#fde68a" }, { background: "transparent" }], { duration: 600 });
}
cart.addEventListener("click", (event) => {
if (!event.target.classList.contains("remove")) return;
const row = event.target.closest(".cart-item");
console.log("removing", row.querySelector(".name").textContent, "| next sibling:", row.nextElementSibling?.querySelector(".name").textContent ?? "none");
row.remove();
updateTotal();
});
updateTotal();
One click listener on the list handles every button, because closest() finds the right row.
Easy way to remember: up = parentElement/closest, down = children/querySelector, sideways = ...ElementSibling.
TL;DR
- Use the
...Element...family; plainnextSibling/childNodesinclude whitespace. closest()up,querySelector()down: the button-finds-its-row pattern.HTMLCollection(live, noforEach) vsNodeList(usually static, hasforEach).- Spread to an array for
map/filter; loop static lists when changing the page. - Animate per frame with a stopping rule;
hidden,animate()andfill: "forwards".
Try this
In Moving elements, set totalFrames to 5. Each frame now moves 40 pixels, and the van still ends at 200, in fewer, bigger jumps.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
nextSibling for the next item | It skips text | Use nextElementSibling | You get #text |
Not checking for null | There is always a sibling | Edges have none | Cannot read properties of null |
| Changing items while looping a live list | The list stays still | It shrinks | Every second item is skipped |
list.map(...) | Collections are arrays | Spread with [...list] | map is not a function |
No end to requestAnimationFrame | It stops by itself | Count frames or check position | The page slows down |
A fade with no fill | The end style stays | Use fill: "forwards" | It snaps back |
Quick reference
| Syntax | Meaning |
|---|---|
el.parentElement | the element directly above, or null |
el.children | the elements directly inside, as a live HTMLCollection |
el.firstElementChild, el.lastElementChild | the first or last element inside, or null |
el.nextElementSibling, el.previousElementSibling | the element directly after or before, or null |
el.childNodes, el.nextSibling | the same idea, but including text nodes |
el.closest(".card") | the nearest ancestor that matches, starting with el itself |
document.getElementsByClassName("x") | a live HTMLCollection |
document.querySelectorAll(".x") | a static NodeList |
list[0], list.item(0), list.length | read one item by position, and count them |
[...list], Array.from(list) | turn a collection into a real array |
requestAnimationFrame(fn) | call fn right before the next frame is drawn |
el.style.transform = "translateX(40px)" | slide an element sideways |
el.hidden = true | hide an element; false shows it again |
el.classList.toggle("is-hidden") | add the class if it is missing, remove it if it is there |
el.animate(keyframes, { duration }) | let the browser animate between styles |
Exercises
What to Remember
- Every element knows its family.
- Collections are not arrays; know live from static.
- Animation = small style changes per frame, with an end.
Next: Import and Export. Split code into modules, share values with export and import, and load modules when needed.