DOM Navigation
Every element in the DOM is connected like a family tree. Move up to parentElement, down through children, or sideways to nextElementSibling.
Parent, children, and siblings
Every element in the DOM is connected like a family tree. Move up to parentElement, down through children, or sideways to nextElementSibling.
Real-life example: In a family photo, you can look at your parent above you, kids below you, or brother/sister beside you — same idea in the DOM tree.
const card = document.querySelector(".lesson-card");
card.parentElement; // wrapper div
card.children; // HTMLCollection of child nodes
card.firstElementChild; // first child element
card.nextElementSibling; // next card beside it
card.previousElementSibling; // previous cardquerySelectorAll
querySelectorAll returns a NodeList of all elements matching a CSS selector. Loop with forEach or convert to an array.
Real-life example: Finding every student wearing a blue uniform in a school photo — one search, many matches.
const buttons = document.querySelectorAll(".course-list button");
buttons.forEach((btn, index) => {
btn.textContent = `Lesson ${index + 1}`;
});
// Change all paragraph colors
document.querySelectorAll("main p").forEach((p) => {
p.style.color = "#334155";
});closest
closest starts from an element and walks up the tree until it finds a match. Great for event delegation on nested clicks.
Real-life example: You touch a leaf on a tree; closest walks up the branch to find the whole tree trunk (parent card or list item).
document.querySelector(".course-list").addEventListener("click", (e) => {
const item = e.target.closest("li");
if (!item) return;
console.log("Clicked lesson:", item.dataset.lessonId);
});dataset — data attributes
HTML data-* attributes store extra info on elements. In JS, use element.dataset — camelCase names (data-lesson-id becomes dataset.lessonId).
Real-life example: Sticky notes on folders — data-course="js" on the HTML tag is a label JavaScript reads without showing it on screen.
<button data-lesson-id="16" data-done="false">Start lesson</button>const btn = document.querySelector("button");
console.log(btn.dataset.lessonId); // "16"
btn.dataset.done = "true"; // updates data-done attribute