The DOM as a Live Tree
See the page the way your script sees it: a tree of live nodes you can query and read, not the HTML file you wrote.
Contentsand lesson path
On this page
- Why it matters
- From markup to nodes
- Finding nodes with selectors
- Reading without changing
- Nodes, elements and text
- Check your understanding
- Apply it
- Review prompt
Lessons of DOM Manipulation & Events
- The DOM as a Live Tree Concept · 15 min
- Changing the Page Safely Worked example · 20 min
- Listeners, Propagation and Default Actions Concept · 25 min
- Lab: A Filterable List Driven by One Delegated Listener Lab · 30 min
- Keeping UI and Data in Sync, and Remembering It Concept · 15 min
- Check: Find and Fix the Interaction Bugs Knowledge check · 6 questions
What you will learn
- Select, create, update and remove DOM nodes, inserting user-supplied text safely with textContent instead of innerHTML.
Prerequisites: JavaScript Foundations
01. Why it matters
You have been writing HTML since the first lessons on semantic markup, and you have styled it with selectors from CSS fundamentals. JavaScript adds a third view of the same page, and it is the one your code actually works with: the DOM, the Document Object Model.
The DOM is not the HTML file. It is the tree of objects the browser builds from that file and keeps in memory. When a script changes a node, the screen changes; when the user or the browser changes something, the tree changes. Every interactive page you will ever build works by querying this tree, reading from it and updating it. If your mental model of the tree is wrong, everything downstream — selectors that find nothing, counts that go stale, text that appears escaped — turns into bugs that are hard to see from the code alone.
This lesson builds the model. The next lessons put it to work: changing the page safely, then reacting to the user.
02. From markup to nodes
As the browser reads your HTML, it creates one object per element, one per run of text, and others for comments and the document itself. The generic name for these objects is node. Elements are nodes, and so is the text inside them. The top-level document object is your entry point to the whole tree.
Take this small page:
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Basket</title></head>
<body>
<h1>Basket</h1>
<ul class="basket">
<li data-sku="APL">Apple</li>
<li data-sku="BAN" class="low">Banana</li>
<li>Pear</li>
</ul>
</body>
</html>The DOM for the body is a tree: body has two element children, the h1 and the ul. The ul has three li children, and each li has a text node inside it. Whitespace between the tags becomes text nodes too, which is why "how many children does this element have" can surprise you when you count raw text nodes; the children collection counts only the elements.
Two properties matter straight away. textContent is all the text in a subtree, concatenated. classList and dataset expose the class attribute and the data-* attributes that your CSS and your own conventions rely on.
03. Finding nodes with selectors
You find nodes with the same selectors you style with. document.querySelector(selector) returns the first match in the document, or null when nothing matches. document.querySelectorAll(selector) returns every match. You can also start from an element: list.querySelectorAll("li") only looks inside list.
A <script> at the end of the body runs after the elements above it exist, so the queries below find what they are looking for. (A script in the head runs before the body is parsed — that ordering problem has solutions, but ending the body with the script is the simplest.)
// Everything the script sees is a node in the live tree.
const list = document.querySelector('.basket');
const items = list.querySelectorAll('li'); // matches inside list only
const heading = document.querySelector('h1');
console.log('count:', items.length);
console.log('heading:', heading.textContent);
console.log('element children:', list.children.length);
const banana = list.querySelector('[data-sku="BAN"]');
console.log('sku:', banana.dataset.sku);
console.log('has .low:', banana.classList.contains('low'));
banana.remove(); // a tree update takes effect at once
console.log('after remove:', list.children.length);count: 3
heading: Basket
element children: 3
sku: BAN
has .low: true
after remove: 2Note the last two lines: banana.remove() takes the node out of the tree, and the very next read reflects it. The DOM is live — the objects in memory are the page, not a copy of it. That single fact explains most of what makes DOM scripting feel different from working with plain data: there is exactly one tree, and everything (your code, the CSS engine, the accessibility tree, other scripts) sees the same one.
One distinction to hold on to for later: querySelectorAll hands you a static list — a snapshot taken at the moment of the call. children is a live view that always reflects the tree as it is now.
const list = document.querySelector('.basket');
const snapshot = document.querySelectorAll('.basket li');
const live = list.children; // always up to date
const extra = document.createElement('li');
extra.textContent = 'Plum';
list.append(extra);
console.log('snapshot:', snapshot.length); // taken earlier
console.log('live:', live.length); // reflects the tree nowsnapshot: 3
live: 404. Reading without changing
A surprising amount of scripting is only reading. Before you reach for an event, you can measure the page: does a certain element exist, what does it say, which items are marked? Reading is also how you debug. In the browser developer tools the document is reachable from the console, so you can try a selector and see what comes back before you put it in your code.
When a query returns null, treat it as a signal, not a nuisance. null from querySelector almost always means one of three things: a typo in the selector, the element is not on this page at all, or the script ran before the element was parsed. The next lesson makes this a habit by building a small page step by step.
05. Nodes, elements and text
You will see the words node and element used almost interchangeably, and most of the time that is harmless. Strictly, node is the generic object in the tree; elements are the nodes that carry a tag name. The text inside an element is not an element — it is one or more text nodes, which is why list.textContent can include the line breaks and indentation from your source file. When you compare or display text you read from the page, remember it may carry that surrounding whitespace, and .trim() is often what you actually want.
The Elements panel of the browser developer tools draws this same tree, and it is the fastest way to build an intuition: select an element there, and the console variable $0 is that very node, ready for .textContent, .children or anything else. The panel and your script cannot disagree, because there is only one tree.
Attributes deserve one note of their own. The class attribute is so common that it gets the dedicated classList object with add, remove, toggle and contains. The data-* attributes get dataset, with dashes turned into camel case. Everything else goes through getAttribute(name) and setAttribute(name, value), which use the attribute name exactly as written in the HTML.
06. Check your understanding
07. Apply it
The practice project for this skill is a vanilla-JavaScript shopping list with add, edit, complete, filter and delete. Open any page you have built so far in the browser and, from the console:
- Select the main heading and read its
textContent. - Count the links with
document.querySelectorAll("a").length, then count only those inside the navigation. - Find an element with a class you styled earlier and confirm
classList.contains(...)agrees with the CSS. - Deliberately query a selector that does not exist and look at what comes back — get used to spotting
null.
08. Review prompt
Without looking back: what is the DOM, and how does it differ from the HTML file? What do querySelector and querySelectorAll return when nothing matches, and what does a script see when it reads them? Explain the difference between a static list and a live view, with one API example of each.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.