Learning Objectives
- Describe the DOM as a bidirectional map between markup and live objects
- Explain what the parse tree is made of: element, text, and comment nodes
- Select an element by id and by CSS selector from
document - Inspect a DOM object with
console.dir()and mutate it withtextContent
The tree is the key
The browser does not keep your markup as text. It parses it into a tree, and hands you an API over that tree. Every individual item in it is a node: elements are nodes, text is a node, comments are nodes — and, the classic surprise, so is the whitespace between your tags. Given this markup:
the tree under the <p> has three children: the text node "The DOM is ", the <em> element (with its own text child "very"), and the text node " powerful!". Elements you indent across several lines pick up extra whitespace-only text children the same way. Nothing about the DOM makes sense until you see the tree this way, and step 3 will make the surprise concrete. For the full story of how the browser gets from bytes to tree, see the browser series.
First contact
document is your entry point into the tree. The two selection calls you will use most, and one mutation, are the whole demo:
console.dir() matters here more than it ever will again: it shows the element as the object it is — hundreds of properties, most of them mapped straight from things you already know how to type in markup. That view is the bidirectional map made visible.
textContent treats the value as plain text, so nothing in it can become markup behind your back. innerHTML parses its value — useful, and hazardous with user input. Step 5 takes this up properly.Live demo
Open your DevTools console first — the two selection buttons deliberately log with console.dir() so you can expand the real object and scroll its properties. Then change the heading's text and note that no “render” call follows: mutating the object is updating the page.
Next Steps
In Step 2: Selection, we work through the whole selection toolbox — the one move every DOM program starts with:
- Climb the method ladder from legacy named access to
querySelectorAll - See a live
HTMLCollectionchange under you while a staticNodeListholds still - Use one selector language for both CSS and JavaScript
- Experiment freely in a selector playground