Lesson 87 of 296
The DOM: select and change elements
What you will learn
- The DOM tree and node types
- Selecting elements
- Moving around the tree
- Reading and changing text, HTML, attributes, classes and styles
- Creating, inserting and removing elements
- Updating the DOM efficiently and safely
On this page
The DOM tree
The DOM represents the page as a tree of nodes. The top is document. Each element is a node with a parent, children and siblings.
<ul id="menu">
<li class="item">Home</li>
<li class="item active">About</li>
</ul>document
html
body
ul#menu
li.item "Home"
li.item.active "About"Node types you will meet:
| Type | Example |
|---|---|
| Element node | <li> |
| Text node | The text "Home" |
| Comment node | <!-- note --> |
| Document node | document |
Selecting elements
| Method | Returns |
|---|---|
document.getElementById("menu") | One element or null |
document.querySelector(".item") | The first match for a CSS selector, or null |
document.querySelectorAll(".item") | All matches, as a static NodeList |
document.getElementsByClassName("item") | All matches, as a live HTMLCollection |
element.querySelector(...) | Searches only inside that element |
querySelector and querySelectorAll accept any CSS selector (Lesson 15):
document.querySelector("#menu li.active");
document.querySelectorAll("input[type='checkbox']:checked");Static vs live lists
- A static
NodeList(fromquerySelectorAll) is a snapshot. It does not change when the page changes. - A live
HTMLCollection(fromgetElementsByClassName,children) updates automatically. Looping over a live list while adding or removing matching elements can cause bugs.
NodeList has forEach. Neither has map or filter, so convert when needed:
const items = [...document.querySelectorAll(".item")];
const texts = items.map((li) => li.textContent);Moving around the tree
| Property | Gives |
|---|---|
el.parentElement | The parent element |
el.children | Child elements (live) |
el.firstElementChild / lastElementChild | First / last child element |
el.nextElementSibling / previousElementSibling | Next / previous sibling element |
el.closest(".card") | The nearest ancestor (or itself) matching a selector |
el.matches(".active") | true if the element matches the selector |
closest is very useful with event delegation (Lesson 88).
Properties without "Element" (childNodes, nextSibling) also include text nodes, such as the spaces between tags, which surprises people.
Text and HTML content
| Property | Reads or sets | Notes |
|---|---|---|
textContent | All text, including hidden elements | Fast. Safe for user data: treats it as text. |
innerText | Only visible text, as it appears | Slower: it needs layout information |
innerHTML | The HTML inside the element | Parses HTML. Dangerous with user data. |
el.textContent = "Hello <b>Sam</b>"; shows the tags as literal text
el.innerHTML = "Hello <b>Sam</b>"; shows Sam in boldinnerHTML and XSS
If you put user-provided text into innerHTML, an attacker can inject HTML that runs JavaScript:
const name = '<img src="x" onerror="stealCookies()">';
greeting.innerHTML = `Hello ${name}`; runs the attacker's code
greeting.textContent = `Hello ${name}`; safe: shown as textThis attack is called XSS (Cross-Site Scripting, Part 20). Rule: use textContent for any text from users or APIs. If you must insert user HTML, clean it with a sanitiser library (such as DOMPurify) first.
Attributes
link.getAttribute("href");
link.setAttribute("href", "/about");
link.removeAttribute("target");
link.hasAttribute("download");Common attributes also exist as properties: img.src, input.value, input.checked, button.disabled, a.href.
Attribute vs property for inputs: the value attribute is the starting value written in the HTML. The value property is the current value after the user types. Read input.value to get what the user typed.
data attributes
Custom data can be stored in data-* attributes and read with dataset:
<button data-product-id="42" data-action="add">Add</button>button.dataset.productId "42" (always a string)
button.dataset.action "add"Hyphenated names become camelCase in dataset.
Classes
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open");
el.classList.toggle("open", isOpen); add if true, remove if false
el.classList.contains("active");
el.classList.replace("old", "new");Prefer changing classes and keeping styles in CSS, over setting inline styles in JavaScript.
Inline styles
el.style.backgroundColor = "red"; CSS names become camelCase
el.style.setProperty("--brand", "teal"); CSS variables
getComputedStyle(el).width; the final value after all CSS rulesel.style only reads inline styles. Use getComputedStyle to read the real value.
Creating and inserting elements
const li = document.createElement("li");
li.textContent = "Contact";
li.classList.add("item");
menu.append(li); add at the end (accepts several nodes and strings)
menu.prepend(li); add at the start
someEl.before(li); insert before someEl
someEl.after(li); insert after someEl
someEl.replaceWith(li); replace someEl
li.remove(); remove it
menu.replaceChildren(); remove all childrenOlder methods you will see: appendChild, insertBefore, removeChild.
insertAdjacentHTML("beforeend", html) adds HTML without destroying existing children. It has the same XSS risk as innerHTML.
Updating efficiently
Each change to the live DOM can trigger layout and paint. For many new elements, build them off the page first, then insert once:
const fragment = document.createDocumentFragment();
for (const product of products) {
const li = document.createElement("li");
li.textContent = product.name;
fragment.append(li);
}
list.append(fragment); one insert into the pageA DocumentFragment is a lightweight container that is not part of the page.
The template element
<template> holds HTML that is not rendered, to be copied by JavaScript:
<template id="row-template">
<li class="row"><span class="name"></span><button>Remove</button></li>
</template>const tpl = document.getElementById("row-template");
const row = tpl.content.cloneNode(true);
row.querySelector(".name").textContent = "Sam";
list.append(row);Common mistakes
querySelectorreturnsnullbecause the script ran before the element existed (usedefer), or the selector is wrong.- Using
innerHTMLwith user data. - Expecting
querySelectorAllresults to havemap. - Reading
el.style.widthand getting an empty string because the width comes from CSS. - Adding hundreds of elements one by one inside a loop.
How to say it in an interview
"The DOM is a tree of nodes representing the page. I select with querySelector and querySelectorAll, which return a static NodeList, and use closest to find ancestors. For text I use textContent, never innerHTML with user data, because that allows XSS. I store custom data in data attributes, toggle classes rather than set inline styles, and build many elements in a DocumentFragment or from a template before inserting them once, to limit reflows."
Key words
| Word | Meaning |
|---|---|
| Node | Any item in the DOM tree |
| Element | A node for an HTML tag |
| NodeList | A list of nodes, static from querySelectorAll |
| HTMLCollection | A live list of elements |
| textContent | The text of an element, safe to set |
| innerHTML | The HTML inside an element, parsed when set |
| XSS | Injecting malicious script into a page |
| dataset | Access to data-* attributes |
| DocumentFragment | An off-page container for building nodes |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.