Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.7 — Traversing the DOM
JavaScript · Example 3 of 3

Up, then down: reading a row from its button

Each button found its own row with closest, then searched down inside that row only. The same function works for any number of rows. In Phase 9 this becomes the click handler.

From any element you can move around the tree: up with parentElement and closest, down with children, firstElementChild and lastElementChild, and sideways with previousElementSibling and nextElementSibling; the element-only versions skip the whitespace text nodes that the plain node versions include.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given an <input id="email"> inside a <div class="field"> that also contains a <label> before it and a <p class="error"> after it, log the label's text and the error's text by traversing from the input.

02

Write textOutline(el) that returns an array of the tag names of all elements inside el (not including el), in document order, using recursion. Test it on a small list.

Explain it without notes

01

What is the difference between nextSibling and nextElementSibling? Why does it matter?

02

How would you find the table row that a clicked button is in, and why is closest better than chaining parentElement?

03

How do you visit every element inside a container, at any depth?

04

What is the difference between parentNode and parentElement?

Up, then down: reading a row from its button

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Lamp costs 499 (column 3)
Chair costs 1299 (column 3)
Chair