DOM Selection & Traversal
Find elements reliably, move through the document tree, and update content without breaking the page.
By the end, you’ll be able to…
- Describe the document as a tree of element and text nodes.
- Select elements with querySelector, querySelectorAll, and getElementById.
- Traverse parents, children, and siblings and convert a NodeList to an array.
- Choose between textContent and innerHTML and guard against missing elements.
01The page becomes a tree
A browser does not keep your HTML as a block of text. After downloading and parsing the file, it builds the Document Object Model: a tree of nodes that represents every element, piece of text, and attribute on the page. The document object is the entry point to that tree. When you write JavaScript that changes a heading or reads a form value, you are working with this live structure rather than with the original file.
Each node has a place in the hierarchy. An element node represents a tag such as main or li; a text node holds the characters between tags. Elements can have a parent, children, and siblings. The distinction between nodes and elements matters because childNodes includes text and comments, while children returns only elements. Most interface code works with elements, so prefer the element-focused properties when you can.
02Three reliable ways to select
getElementById is the most direct selection method: give it an id and it returns the matching element or null. querySelector accepts any CSS selector and returns the first matching element or null. querySelectorAll returns every match in a static NodeList. Because selectors can express relationships and attributes, querySelector often replaces several older lookup methods with one readable line.
Keep selectors narrow and stable. An id is a strong hook for a single landmark, while a class or data attribute suits repeated components. Calling querySelector on an element searches only that element's descendants, which keeps a component's code local. Avoid selecting by deep tag chains that break when the markup changes. Prefer a dedicated hook such as data-role='status' over a long path of divs.
03Walking the tree
parentElement moves up one level; children, firstElementChild, and lastElementChild move down. nextElementSibling and previousElementSibling move sideways. Their node counterparts, parentNode and nextSibling, may land on whitespace text nodes, which is rarely what interface logic wants. Choose one family of properties and stay consistent so your traversal code remains predictable.
querySelectorAll returns a NodeList, not an array. It supports forEach and has a length, which covers many loops, but map, filter, and sort require a real array. Convert with Array.from(nodes) or the spread syntax. Also note freshness: a NodeList from querySelectorAll does not update when the page changes, whereas an element's children collection is live. Re-query or rebuild your array after adding nodes.
04Content, safety, and missing elements
textContent reads or writes the text inside an element without interpreting markup. Setting it removes existing child nodes and inserts a single text node, so user input stays visible text instead of becoming executable HTML. innerHTML parses a string as markup. That is convenient for trusted templates, but inserting user-provided content this way creates a cross-site scripting risk. Default to textContent for anything a person can type.
Any selector can miss. querySelector returns null when nothing matches, and calling a property on null stops your script with a TypeError. Check the result before using it. Optional chaining helps for reads, as in heading?.textContent, but writes need a real guard. If an element is required, fail loudly during setup so the mistake is found in development rather than hidden behind silence.
The ideas worth keeping.
- The DOM is a live tree; select elements from it with CSS selectors or ids.
- Use element-focused traversal properties and convert NodeLists to arrays before using array methods.
- Prefer textContent for untrusted text, and check for null before treating a selection as an element.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Summarise a reading list
Assume the page contains a ul with the id reading-list and three li children. Write a script that selects the list, converts its element children into an array, trims each title, converts it to uppercase, and logs a single line such as '3 books: HTML BASICS, CSS LAYOUT, JAVASCRIPT EVENTS'. Throw a clear error if the list is missing.
Explore a worked solution
const list = document.getElementById("reading-list");if (!list) throw new Error("Reading list not found");const titles = Array.from(list.children).map((item) => item.textContent.trim().toUpperCase());console.log(titles.length + " books: " + titles.join(", "));children gives only element nodes, and Array.from makes map available. Trimming removes indentation whitespace, and join builds the summary without another loop.
Exercise 2: Report status safely
Write a function setStatus(text) that finds the element with id status. If it exists, replace its text and return true. If it does not exist, log a warning and return false. Call the function once with 'Ready'.
Explore a worked solution
function setStatus(text) { const status = document.querySelector("#status"); if (!status) { console.warn("Status element not found"); return false; } status.textContent = text; return true;}setStatus("Ready");The guard runs before any property access, so the function cannot throw when the element is absent. Returning a boolean lets callers react to the failure.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Summarise a reading list
Assume the page contains a ul with the id reading-list and three li children. Write a script that selects the list, converts its element children into an array, trims each title, converts it to uppercase, and logs a single line such as '3 books: HTML BASICS, CSS LAYOUT, JAVASCRIPT EVENTS'. Throw a clear error if the list is missing.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.