Understanding the DOMLesson 1.4
How to traverse the DOM tree with parent, child, and sibling properties
parentElement, children, firstElementChild, lastElementChild, nextElementSibling, previousElementSibling, closest
Traversing the DOM Tree
Traversal properties let you navigate the tree relative to a known node — useful when you cannot predict exact IDs or classes.
Moving Up and Down
const item = document.querySelector('.active');
// Go up
console.log(item.parentElement);
// Go down
console.log(item.children); // HTMLCollection of child elements
console.log(item.firstElementChild);
console.log(item.lastElementChild);Moving Sideways
console.log(item.nextElementSibling);
console.log(item.previousElementSibling);closest() — Walk Up Until Match
closest(selector) starts at the current element and walks up the tree, returning the first ancestor that matches the selector — or null if none found. It is the cleanest way to find a containing component from a deeply nested click target.
// User clicks a button inside a .card div
document.querySelector('button').addEventListener('click', function(e) {
const card = e.target.closest('.card');
card.classList.add('selected');
});Prefer closest over manual parentElement chains. It is shorter, more readable, and does not break if you add nesting layers later.
