Chapter 9 of 34
~11 minThe DOM & DOM Manipulation
The DOM (Document Object Model) is the browser's live, in-memory representation of your page as a tree of objects. JavaScript reads and modifies this tree to make pages dynamic - and that skill is the backbone of front-end development.
What the DOM Is
When a browser loads HTML, it parses the markup into a tree of node objects - elements, text, attributes - called the DOM. This tree is separate from the original HTML source; JavaScript interacts with the tree, and the browser re-renders the page whenever the tree changes.
Selecting Elements
`document.getElementById('id')` finds a single element by its id. `document.querySelector('.class')` finds the first element matching any CSS selector, and `document.querySelectorAll('.class')` returns all matches as a NodeList. `querySelector`/`querySelectorAll` are more flexible since they accept any valid CSS selector.
Try it yourself
Selecting and reading an element<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div> <p class="greeting">Original text</p>
Creating and Appending Elements
`document.createElement('tag')` creates a new, detached element. You set its content and attributes, then attach it to the visible tree with methods like `appendChild`, `append`, or `prepend`. `element.remove()` takes it back out.
Try it yourself
Building a list item dynamically<ul id="list"><li>Existing item</li></ul>
Changing Text, Attributes, and Classes
`textContent` sets/reads plain text, while `innerHTML` sets/reads markup (and should be used carefully, since inserting untrusted HTML can introduce security issues). `element.setAttribute(name, value)` changes an attribute, and `classList.add/remove/toggle` manages CSS classes without touching the whole `class` string by hand.
Try it yourself
Toggling a class and updating text<p id="msg">Click the button to highlight me</p> <button id="toggleBtn">Toggle Highlight</button>
Coding challenge
Given a <ul id="list"> with one existing <li>, write JavaScript that creates two new <li> elements with the text "Item 2" and "Item 3", and appends both to the list.
<ul id="list"><li>Item 1</li></ul>
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/41. What is the DOM?
2. Which method finds ALL elements matching a CSS selector?
3. What is the safer property to use when you only need to set plain text (not markup)?
4. Which method creates a new, detached DOM element?