Behind every web page, the browser keeps a live model of it called the DOM (Document Object Model): a family tree of objects, one for each tag, built as the HTML is read. JavaScript can walk this tree to find any element, read it and change it. Rewriting a heading, adding items to a list, switching a CSS class or deleting an element all go through the DOM, and the screen updates at once with no reload.
In this lesson you will learn
- What the DOM tree is
- Selecting elements with
querySelectorandgetElementById - Changing text, HTML, styles and classes
- Creating, adding and removing elements
- Reading and setting attributes and
data-*values
The DOM Tree
For a page with a heading and a list, the browser builds a tree like this:
document
└── html
├── head
│ └── title
└── body
├── h3#title
└── ul#list
├── li
└── li
The global document object is the root. Every element is an object with properties (textContent, id, style) and methods (append(), remove()).
Selecting and Changing Elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM</title>
<style>
body { font-family: sans-serif; }
.done { text-decoration: line-through; color: #888; }
.highlight { background: #fff3cd; }
</style>
</head>
<body>
<h3 id="title">Shopping list</h3>
<ul id="list">
<li>Rice</li>
<li>Eggs</li>
</ul>
<p class="note">Items are added by JavaScript below.</p>
<script>
const title = document.querySelector("#title");
title.textContent = "Shopping list (updated by JS)";
title.style.color = "#00695c";
const list = document.querySelector("#list");
for (const item of ["Milk", "Bread"]) {
const li = document.createElement("li");
li.textContent = item;
list.appendChild(li);
}
const items = document.querySelectorAll("#list li");
items[0].classList.add("done");
document.querySelector(".note").classList.add("highlight");
document.querySelector(".note").textContent += " Total items: " + items.length;
</script>
</body>
</html>
Result
document.querySelector("#title")returns the first element matching a CSS selector. It accepts any selector you would use in CSS, such as.noteorul li.document.querySelectorAll("#list li")returns all matches as a list you can loop over withfor...ofor index like an array.textContentreads or replaces an element’s text.style.colorsets an inline style; CSS property names become camelCase, sobackground-colorisstyle.backgroundColor.document.createElement("li")makes a new element, andappendChild()(orappend()) puts it into the page.classList.add(),remove()andtoggle()switch CSS classes. Changing classes is usually cleaner than setting many inline styles.
Content, Attributes and Removing
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM attributes</title>
<style>body { font-family: sans-serif; } .box { padding: 8px; border: 2px solid #6a1b9a; }</style>
</head>
<body>
<div class="box" id="box">Original <b>bold</b> text</div>
<a id="link" href="#first">A link</a>
<pre id="log"></pre>
<script>
const box = document.getElementById("box");
const link = document.getElementById("link");
const log = document.getElementById("log");
log.textContent += "textContent: " + box.textContent + "\n";
log.textContent += "innerHTML: " + box.innerHTML + "\n";
link.setAttribute("href", "#second");
log.textContent += "href is now: " + link.getAttribute("href") + "\n";
box.dataset.status = "checked";
log.textContent += "data-status: " + box.dataset.status + "\n";
box.style.background = "#f3e5f5";
box.remove();
log.textContent += "box removed; still in page? " + document.body.contains(box);
</script>
</body>
</html>
Result
textContentgives only the text;innerHTMLgives the HTML markup inside the element.getAttribute()andsetAttribute()read and write any attribute, such ashreforsrc.datasetreads and writesdata-*attributes:dataset.statusmaps todata-status. They are handy for storing small bits of information on elements.element.remove()takes an element out of the page.
DOM Cheat Sheet
| Task | Code |
|---|---|
| Find one element | document.querySelector(".card") |
| Find all | document.querySelectorAll(".card") |
| Change text | el.textContent = "Hi" |
| Toggle a class | el.classList.toggle("open") |
| Create and add | parent.append(document.createElement("p")) |
| Remove | el.remove() |
| Read a form value | input.value |
Common Mistakes
- Running the script before the HTML exists, so
querySelectorreturnsnull. Put scripts at the end of the body or usedefer. - Forgetting the
#or.inquerySelector. (getElementByIdtakes the id without#.) - Treating
querySelectorAllas one element:list.textContent = "x"does nothing useful; loop over it. - Putting user input into
innerHTML, which can run malicious HTML. UsetextContentfor text.
Practice Exercises
Exercise 1. Change the text of every <p> with class price to “Sold out”.
Show answer
for (const p of document.querySelectorAll("p.price")) {
p.textContent = "Sold out";
}
Exercise 2. Build a <ul> from the array ["HTML", "CSS", "JS"] and add it to the body.
Show answer
const ul = document.createElement("ul");
for (const topic of ["HTML", "CSS", "JS"]) {
const li = document.createElement("li");
li.textContent = topic;
ul.append(li);
}
document.body.append(ul);
Frequently Asked Questions
Should I use getElementById or querySelector?
Both work. getElementById is slightly faster and only finds by id; querySelector accepts any CSS selector, so many developers use it everywhere for consistency.
Is the DOM part of JavaScript?
No. The DOM is a browser feature that JavaScript can use. That is why document does not exist when you run code in Node.js.
Summary
- The DOM is the browser’s tree of objects built from HTML.
querySelectorandquerySelectorAllfind elements with CSS selectors.- Change pages with
textContent,classList,styleand attributes. createElement,appendandremoveadd and delete elements.
Next: JavaScript Events.
