Walking the Tree

Grade 11, page 8 of 10. A one-minute read.

Since the DOM is a family tree, every element knows its relatives. You can move around the tree from any element:

PropertyGives you
element.parentElementIts parent
element.childrenA list of its child elements
element.firstElementChildIts first child
element.lastElementChildIts last child
element.nextElementSiblingThe sibling right after it
element.previousElementSiblingThe sibling right before it
element.closest(selector)The nearest ancestor (or itself) that matches the selector
JavaScript
const favorite = document.querySelector(".favorite");

console.log(favorite.parentElement.id);                   // "food-list"
console.log(favorite.previousElementSibling.textContent); // "Omelet"
console.log(favorite.parentElement.children.length);      // 3

You won't need these every day, but closest in particular will be very useful in Grade 12.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning