# DOM Traversal, Collections and Animation

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: DOM Manipulation
Source: https://www.devtutorials.ai/learn/javascript/dom/dom-traversal-collections-and-animation

> 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 (`HTMLCollection` or `NodeList`). 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.

<figure className="ts-fig">
  <svg viewBox="0 0 560 180" role="img" aria-label="A family tree: a ul parent with three li children. A highlight moves from the middle child up to the parent, then to the siblings on each side." width="100%">
    <rect x="0" y="0" width="560" height="180" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="215" y="20" width="130" height="34" rx="8" fill="#1e3a8a" /><text x="280" y="42" textAnchor="middle" fontSize="12" fill="#ffffff">ul (parent)</text>
    <line x1="280" y1="54" x2="120" y2="100" stroke="#94a3b8" strokeWidth="2" /><line x1="280" y1="54" x2="280" y2="100" stroke="#94a3b8" strokeWidth="2" /><line x1="280" y1="54" x2="440" y2="100" stroke="#94a3b8" strokeWidth="2" />
    <rect x="60" y="100" width="120" height="34" rx="8" fill="#eff6ff" stroke="#2563eb" /><text x="120" y="122" textAnchor="middle" fontSize="12" fill="#1e40af">Rice</text>
    <rect x="220" y="100" width="120" height="34" rx="8" fill="#fef3c7" stroke="#d97706" /><text x="280" y="122" textAnchor="middle" fontSize="12" fill="#92400e">Milk (me)</text>
    <rect x="380" y="100" width="120" height="34" rx="8" fill="#eff6ff" stroke="#2563eb" /><text x="440" y="122" textAnchor="middle" fontSize="12" fill="#1e40af">Bread</text>
    <text x="120" y="160" textAnchor="middle" fontSize="11" fill="#475569">previousElementSibling</text>
    <text x="280" y="160" textAnchor="middle" fontSize="11" fill="#475569">parentElement ↑</text>
    <text x="440" y="160" textAnchor="middle" fontSize="11" fill="#475569">nextElementSibling</text>
    <circle r="8" fill="#dc2626"><animate attributeName="cx" values="280;280;120;440;280" keyTimes="0;0.25;0.5;0.75;1" dur="4s" repeatCount="indefinite" /><animate attributeName="cy" values="117;37;117;117;117" keyTimes="0;0.25;0.5;0.75;1" dur="4s" repeatCount="indefinite" /></circle>
  </svg>
  <figcaption>From "me", step up to the parent or sideways to the siblings.</figcaption>
</figure>

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

1. Parent, child and sibling navigation, and walking the tree.
2. Nodes versus elements, and finding nearby elements with `closest()`.
3. `HTMLCollection` and `NodeList`, live versus static.
4. Looping, reading by position, and converting to an array.
5. 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.

```dom runnable title="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:

```text
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>`:

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
Removing Tea towel (₹199)
Items left: 1
```

### parentElement

The element directly above. Here a ticked checkbox colours its row.

```dom runnable title="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:

```text
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`.

```dom runnable title="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:

```text
Songs: 3
- Morning Raga
- Monsoon Song
- Evening Walk
```

### firstElementChild

The first element inside, or `null` when empty.

```dom runnable title="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:

```text
Leader: 👑 Asha - 920 points
First child of an empty list: null
```

### lastElementChild

The last element inside: always the newest message in a chat.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
Can I return a mug? → Yes, within 30 days.
```

### previousElementSibling

The element straight before, or `null` at the top. Great for "move up" buttons.

```dom runnable title="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:

```text
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()`.

```dom runnable title="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:

```text
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()`.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
Before - live: 2 | static: 2
After  - live: 3 | static: 2
```

A loop that changes the page can trip over a live collection:

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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()`.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
Setting off from: translateX(0px)
Arrived: translateX(200px)
```

### Showing and hiding elements

`el.hidden = true` hides; `false` shows. `!details.hidden` flips it.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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.

```dom runnable title="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:

```text
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()`.

```js runnable preview="cart" title="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; plain `nextSibling`/`childNodes` include whitespace.
- `closest()` up, `querySelector()` down: the button-finds-its-row pattern.
- `HTMLCollection` (live, no `forEach`) vs `NodeList` (usually static, has `forEach`).
- Spread to an array for `map`/`filter`; loop static lists when changing the page.
- Animate per frame with a stopping rule; `hidden`, `animate()` and `fill: "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

<div className="tscroll">

| 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 |

</div>

## 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.
