JavaScript DOM manipulation
What the DOM is and how JavaScript changes a page through it: the tree a browser builds from HTML, document and querySelector, textContent against innerHTML, attributes, querySelectorAll and NodeList, classList, createElement and append, and why a script in the head finds null.
In this lesson
Here’s a web page for a rocket called Kestrel. It’s one HTML file, kestrel.html, with a heading, a fuel gauge and a crew list:
<!DOCTYPE html>
<html>
<head>
<title>Kestrel</title>
<link rel="stylesheet" href="kestrel.css">
</head>
<body>
<h1>Kestrel: on the pad</h1>
<progress id="fuel" value="80" max="100"></progress>
<ul>
<li>Ada</li>
<li>Lee</li>
<li>Omar</li>
</ul>
<script src="mission.js"></script>
</body>
</html>
It loads a stylesheet, kestrel.css, which holds one rule:
.aboard { color: green; }
And it loads a script, mission.js, two lines long:
const heading = document.querySelector("h1");
heading.textContent = "Kestrel: liftoff";
Open the page, and the heading reads Kestrel: liftoff. The page didn’t reload. Now open kestrel.html in an editor, or pick View Source in the browser. It still says on the pad. Nothing in the file has changed.
So if the script didn’t change the file, what did it change? The answer is the DOM. By the end of this lesson you’ll know what the DOM is, how a script finds elements in it, and how to change them: their text, their attributes and their classes, and how to add elements the file never had.
To follow along, save those three files in one folder and open kestrel.html in a browser. Each example below is the whole of mission.js: replace what’s in it, save, and reload the page. What it prints shows in the console of the browser’s developer tools.
The DOM
A browser doesn’t draw an HTML file. HTML is text: tags, with more tags nested inside them. The browser reads that text from the top, and for every tag it builds an object. One for the body. Inside it, one for the heading, one for the fuel gauge, and one for the list, which holds one for each crew member. The words between the tags get objects of their own.
Each object is called a node. A node that came from a tag is an element, and a node that holds words is a text node. Together they make a tree:
document
└─ html
├─ head
│ ├─ title
│ └─ link
└─ body
├─ h1 ── "Kestrel: on the pad"
├─ progress
├─ ul
│ ├─ li ── "Ada"
│ ├─ li ── "Lee"
│ └─ li ── "Omar"
└─ script
The line breaks between tags become text nodes too. This picture leaves them out.
The tree has a name: the Document Object Model. Everyone calls it the DOM. What you see on screen is drawn from that tree, not from the file. And the DOM doesn’t come with JavaScript. The browser builds it, and gives your script a way in. Where there’s no page there’s no DOM: run the two lines above in Node, and you get ReferenceError: document is not defined.
The document object
That way in is one object, called document. It stands for the whole page, and it sits at the top of the tree. It’s a JavaScript object like any other, with properties and methods:
console.log(document.title); // Kestrel
console.log(document.body === document.querySelector("body")); // true
document.title is the text on the browser tab. document.body is the body element. Every element has properties that lead to its neighbors. children holds the elements inside it, and parentElement is the one it sits in:
const first = document.body.children[0];
console.log(document.body.children.length); // 4
console.log(first.textContent); // Kestrel: on the pad
console.log(first.parentElement === document.body); // true
The body has four children, because the script tag is an element too. So you can walk the tree a step at a time. But a walk like that breaks as soon as someone adds a tag to the page: put <p>Launch day</p> above the heading, and document.body.children[0] is that paragraph. So most code doesn’t walk. It searches.
Finding an element
The search is a method of document: querySelector. You hand it a selector, a short pattern that describes the element you want. CSS, the language that styles a page, picks elements with the same patterns:
- A tag name, like
"h1", matches elements with that tag. - A dot and a name, like
".aboard", matches a class. - A hash and a name, like
"#fuel", matches the element with that id.
querySelector goes through the tree from the top, and stops at the first element that fits:
const heading = document.querySelector("h1");
console.log(heading.textContent); // Kestrel: on the pad
console.log(document.querySelector("li").textContent); // Ada
console.log(document.querySelector("#fuel").id); // fuel
console.log(document.querySelector(".aboard")); // null
The page has three list items, and you get the first. Nothing on it has the class aboard yet, so that search has nothing to return, and you get null.
What you get back is the element itself. Not a copy. Your variable and the tree now hold the same object, so a change made through one shows up in the other. Older code uses getElementById, which takes the id with no hash in front, and finds the same element:
console.log(document.getElementById("fuel") === document.querySelector("#fuel")); // true
Every element has querySelector too. Called on an element, it searches inside that element only:
const list = document.querySelector("ul");
console.log(list.querySelector("li").textContent); // Ada
console.log(list.querySelector("h1")); // null
Changing text
Once you hold an element, you can change it. Start with its text. The property is textContent. Read it, and you get a string: the text the element holds. Assign a new string, and the text in the tree is replaced:
const heading = document.querySelector("h1");
console.log(heading.textContent); // Kestrel: on the pad
heading.textContent = "Kestrel: liftoff";
console.log(heading.textContent); // Kestrel: liftoff
Those are the two lines this lesson opened with. The first found the heading. The second gave it new text. Then the browser redrew the heading from the tree. No request went to a server, and nobody opened the file again. That’s why the file still says on the pad. A script doesn’t edit HTML. It edits the tree that the HTML turned into.
Text or HTML
textContent treats whatever you give it as plain text. Give it a string with a tag in it, and the page shows the tag, angle brackets and all:
const heading = document.querySelector("h1");
heading.textContent = "Kestrel: <em>liftoff</em>";
console.log(heading.children.length); // 0
The heading has no element inside it, only text, and the page reads Kestrel: <em>liftoff</em>. A second property, innerHTML, reads the string as HTML. It runs it through the browser’s HTML parser, the same code that read the file, and builds real elements from it:
const heading = document.querySelector("h1");
heading.innerHTML = "Kestrel: <em>liftoff</em>";
console.log(heading.children.length); // 1
console.log(heading.textContent); // Kestrel: liftoff
Now the heading holds an em element, and the page shows liftoff in italics. That’s handy, and it’s also how pages get attacked. If any part of that string was typed by a visitor, they can add elements of their own to your page, including ones that run their code:
const typed = '<img src="x" onerror="alert(document.title)">';
const item = document.querySelector("li");
item.innerHTML = typed; // the image fails to load, and its onerror code runs
That builds an image nobody on your side wrote. Its address leads nowhere, so loading it fails, and that sets off the code in its onerror attribute: an alert box opens showing the page’s own title. This code is harmless. An attacker’s wouldn’t be. The attack has a name: cross-site scripting, or XSS. A <script> tag added through innerHTML doesn’t run, but an onerror attribute does.
Hand the same string to textContent, and nothing runs:
const typed = '<img src="x" onerror="alert(document.title)">';
const item = document.querySelector("li");
item.textContent = typed; // shows as text
console.log(item.children.length); // 0
So set text with textContent, and keep innerHTML for HTML you wrote yourself. A third property, innerText, reads only the text the page shows, where textContent also returns text that CSS has hidden.
Attributes
A tag can carry attributes: names with values, written inside it. This progress tag is Kestrel’s fuel gauge, with a value of 80 and a max of 100:
<progress id="fuel" value="80" max="100"></progress>
They come into the tree with the tag, and on the element, each of them is a property. gauge.value is the number 80. Set it to 100, and the bar on the page fills up:
const gauge = document.querySelector("#fuel");
console.log(gauge.value); // 80
gauge.value = 100;
console.log(gauge.value); // 100
Two methods work on any attribute, by name: getAttribute and setAttribute.
const gauge = document.querySelector("#fuel");
console.log(gauge.getAttribute("max")); // 100
console.log(typeof gauge.getAttribute("max")); // string
console.log(typeof gauge.max); // number
gauge.setAttribute("value", "95");
console.log(gauge.value); // 95
They differ from the property in one way. getAttribute always returns a string, because in HTML every value is text. The property gives you a type you can work with: here, a number. One pair has two names: the class attribute is the className property.
Finding every match
querySelector stops at the first match. querySelectorAll returns every one. Ask for the list items, and you get the three crew members, top to bottom:
const items = document.querySelectorAll("li");
console.log(items.length); // 3
console.log(items[0].textContent); // Ada
What comes back looks like an array: it has a length, and you can read item zero. It isn’t one. It’s a NodeList, and it has no map and no filter:
const items = document.querySelectorAll("li");
console.log(Array.isArray(items)); // false
items.map((item) => item.textContent);
// Uncaught TypeError: items.map is not a function
A NodeList is iterable, though: it can hand out its items one at a time, as the episode on iterators showed. So a for…of loop walks it, and the three dots of spread turn it into a real array. Now map works, and the crew on the page becomes an array of names:
const items = document.querySelectorAll("li");
for (const item of items) {
console.log(item.textContent);
}
// Ada
// Lee
// Omar
const names = [...items].map((item) => item.textContent);
console.log(names); // ["Ada", "Lee", "Omar"]
A NodeList does have forEach. And it’s a snapshot: an element added to the page later isn’t in it.
Classes and styles
The attribute you’ll change most is class. A class is a label, and the page’s stylesheet, its CSS file, says what the label looks like. In this one, anything with the class aboard is green:
.aboard { color: green; }
Every element has a classList, with three methods you’ll use all the time: add, remove and toggle. Loop over the crew, add aboard to each one, and the names turn green:
const items = document.querySelectorAll("li");
for (const item of items) {
item.classList.add("aboard");
}
console.log(items[0].className); // aboard
Notice the word the script never used: green. It said who’s aboard, and the stylesheet decided how that looks. remove takes the class off again, and toggle adds it if it’s missing and removes it if it’s there:
const items = document.querySelectorAll("li");
items[0].classList.add("aboard");
items[0].classList.remove("aboard");
console.log(items[0].classList.contains("aboard")); // false
items[0].classList.toggle("aboard");
console.log(items[0].classList.contains("aboard")); // true
You can also set a style straight on an element, with its style property:
const heading = document.querySelector("h1");
heading.style.color = "green";
console.log(heading.getAttribute("style")); // color: green;
That writes the style onto the one element, as if its tag read <h1 style="color: green;">. A CSS name with a hyphen in it is spelled in camelCase here: background-color is style.backgroundColor. That’s fine for a one-off. For everything else, change the class.
Creating elements
Every element so far came from the file. A script can make new ones. Call document.createElement with a tag name, and you get an element. It’s a real object, but it isn’t in the tree yet, so it isn’t on the page. Give it some text, then call append on the list, and the new element joins the tree as the list’s last child:
const list = document.querySelector("ul");
const item = document.createElement("li");
item.textContent = "Zoe";
console.log(list.children.length); // 3
list.append(item);
console.log(list.children.length); // 4
Zoe is on the page. To take an element out again, call remove on it:
const list = document.querySelector("ul");
const item = document.createElement("li");
item.textContent = "Zoe";
list.append(item);
item.remove();
console.log(list.children.length); // 3
console.log(item.textContent); // Zoe
The element has left the tree, but the variable still holds it, text and all. Two more things worth knowing: older code says appendChild, which takes one node at a time, and an element lives in one place, so if you append one that’s already on the page, it moves.
Put those steps in a loop, and you can build a page from data. Start with an empty list in the file:
<ul></ul>
Then take an array of names, and make one item for each:
const crew = ["Ada", "Lee", "Omar"];
const list = document.querySelector("ul");
for (const name of crew) {
const item = document.createElement("li");
item.textContent = name;
list.append(item);
}
console.log(list.children.length); // 3
The file never had a crew. The page does.
When a script runs
One error catches almost everyone. Move the script tag up, out of the body and into the head:
<head>
<title>Kestrel</title>
<link rel="stylesheet" href="kestrel.css">
<script src="mission.js"></script>
</head>
Now the same two lines throw:
const heading = document.querySelector("h1");
heading.textContent = "Kestrel: liftoff";
// Uncaught TypeError: Cannot set properties of null (setting 'textContent')
Here’s what happened. The browser builds the tree while it reads the file. When it gets to a script tag, it stops building and runs the script. At that moment, the tree has a head and no body. There’s no heading to find, so querySelector returns null, and null has no properties to set.
There are three ways out:
- Leave the script tag as the last thing in the body. By the time the browser reaches it, everything above it is in the tree.
- Add the word
deferto the tag, and the browser runs the script once the tree is complete.deferneeds asrc: on a script written inline, it does nothing. - Make the script a module, with
type="module". A module waits for the tree without being told. Opened straight from disk, a module file is blocked, so the page needs a server, as the episode on modules showed.
<script src="mission.js" defer></script>
<script type="module" src="mission.js"></script>
Back to the page
Which brings us back to the page we started with. Its file says on the pad. Its heading says liftoff. Both are right. The file is where the tree starts, and from then on, the tree is the page. A script can change any part of it, and the browser draws whatever the tree holds.
Reload, and that tree is thrown away. The browser reads the file again, builds a new tree, and runs the script again.
You can look at both. View Source shows the file. The Elements panel in DevTools shows the tree. Look at the source of a large web app, and you’ll often find a file that’s almost empty:
<body>
<div id="app"></div>
<script src="app.js"></script>
</body>
Nearly everything on screen was put there by JavaScript, in the DOM.
Summary
- A browser turns a page’s HTML into a tree of objects, the DOM, and draws the page from that tree. A script changes the tree, never the file.
documentis the way in.childrenandparentElementwalk the tree, but most code searches it.querySelectortakes a selector (a tag name,.classor#id) and stops at the first element that fits, or gives younull.querySelectorAllreturns every match in a NodeList, which is iterable but isn’t an array.textContentsets plain text.innerHTMLparses its string as HTML, so it’s only for HTML you wrote yourself.- An attribute in the HTML is a property on the element.
getAttributealways returns a string; the property has a useful type. classList.add,removeandtogglechange an element’s classes, and the stylesheet decides how a class looks. Thestyleproperty styles one element directly.document.createElementmakes an element,appendputs it in the tree, andremovetakes it out.- A script runs where the parser meets it. In the head, the body isn’t built yet, so
querySelectorfindsnull. Put the script last in the body, or usedeferortype="module".
Video transcript
Intro
Here's a web page for a rocket called Kestrel. Its heading reads: Kestrel, on the pad. Two lines of JavaScript run, and the heading reads: Kestrel, liftoff. The page didn't reload. Now open the page's HTML file. It still says on the pad. Nothing in the file has changed. So if the script didn't change the file, what did it change? Today, we find out.
By the end of this video, you'll understand three things. One: the DOM: the tree of objects a browser builds from a page's HTML, and why changing that tree changes the page. Two: how a script finds elements in the tree, with querySelector and querySelectorAll, and what it gets back. Three: how to change them: their text, their attributes and their classes, and how to add elements the file never had.
The DOM
A browser doesn't draw an HTML file. HTML is text: tags, with more tags nested inside them. The browser reads that text from the top, and for every tag it builds an object. One for the body. Inside it, one for the heading, one for the fuel gauge, and one for the list, which holds one for each crew member. The words between the tags get objects of their own. Each object is called a node, and a node that came from a tag is an element. Together they make a tree, and the tree has a name: the Document Object Model. Everyone calls it the DOM. What you see on screen is drawn from that tree, not from the file. And the DOM doesn't come with JavaScript. The browser builds it, and gives your script a way in.
The document object
That way in is one object, called document. It stands for the whole page, and it sits at the top of the tree. It's a JavaScript object like any other, with properties and methods. document dot title is the text on the browser tab. document dot body is the body element. Every element has properties that lead to its neighbors: children holds the elements inside it, and parentElement is the one it sits in. So you can walk the tree a step at a time. But a walk like that breaks as soon as someone adds a tag to the page. So most code doesn't walk. It searches.
Finding an element
The search is a method of document: querySelector. You hand it a selector, a short pattern that describes the element you want. CSS, the language that styles a page, picks elements with the same patterns. A tag name, like h1, matches elements with that tag. A dot and a name matches a class. A hash and a name matches the element with that id. querySelector goes through the tree from the top, and stops at the first element that fits. What you get back is the element itself. Not a copy. Your variable and the tree now hold the same object, so a change made through one shows up in the other. If nothing matches, you get null. Older code uses getElementById, which takes the id with no hash in front, and finds the same element.
Changing text
Once you hold an element, you can change it. Start with its text. The property is textContent. Read it, and you get a string: the text the element holds. Assign a new string, and the text in the tree is replaced. Those are the two lines we opened with. The first found the heading. The second gave it new text. Then the browser redrew the heading from the tree. No request went to a server, and nobody opened the file again. That's why the file still says on the pad. A script doesn't edit HTML. It edits the tree that the HTML turned into.
Text or HTML
textContent treats whatever you give it as plain text. Give it a string with a tag in it, and the page shows the tag, angle brackets and all. A second property, innerHTML, reads the string as HTML. It runs it through the browser's HTML parser, the same code that read the file, and builds real elements from it. That's handy, and it's also how pages get attacked. If any part of that string was typed by a visitor, they can add elements of their own to your page, including ones that run their code. So set text with textContent, and keep innerHTML for HTML you wrote yourself.
Attributes
A tag can carry attributes: names with values, written inside it. This progress tag is Kestrel's fuel gauge, with a value of eighty and a max of a hundred. They come into the tree with the tag, and on the element, each of them is a property. gauge dot value is the number eighty. Set it to a hundred, and the bar on the page fills up. Two methods work on any attribute, by name: getAttribute and setAttribute. They differ from the property in one way. getAttribute always returns a string, because in HTML every value is text. The property gives you a type you can work with: here, a number.
Finding every match
querySelector stops at the first match. querySelectorAll returns every one. Ask for the list items, and you get the three crew members, top to bottom. What comes back looks like an array: it has a length, and you can read item zero. It isn't one. It's a NodeList, and it has no map and no filter. Call map on it, and you get a TypeError: map is not a function. A NodeList is iterable, though. So a for of loop walks it, and the three dots of spread turn it into a real array. Now map works, and the crew on the page becomes an array of names.
Classes and styles
The attribute you'll change most is class. A class is a label, and the page's stylesheet, its CSS file, says what the label looks like. In this one, anything with the class aboard is green. Every element has a classList, with three methods you'll use all the time: add, remove and toggle. Loop over the crew, add aboard to each one, and the names turn green, one after another. Notice the word the script never used: green. It said who's aboard, and the stylesheet decided how that looks. You can also set a style straight on an element, with its style property. That's fine for a one-off. For everything else, change the class.
Creating elements
Every element so far came from the file. A script can make new ones. Call document dot createElement with a tag name, and you get an element. It's a real object, but it isn't in the tree yet, so it isn't on the page. Give it some text: Zoe. Then call append on the list, and the new element joins the tree as the list's last child. Zoe is on the page. To take an element out again, call remove on it. Put those steps in a loop, and you can build a page from data. Start with an empty list and an array of names, and make one item for each. The file never had a crew. The page does.
When a script runs
One error catches almost everyone. Move the script tag up, out of the body and into the head, and the same two lines throw. TypeError: Cannot set properties of null. Here's what happened. The browser builds the tree while it reads the file. When it gets to a script tag, it stops building and runs the script. At that moment, the tree has a head and no body. There's no heading to find, so querySelector returns null, and null has no properties to set. There are three ways out. Leave the script tag as the last thing in the body. Or add the word defer to the tag, and the browser runs the script once the tree is complete. Or make the script a module, with type equals module. A module waits for the tree without being told.
Back to the page
Which brings us back to the page we started with. Its file says on the pad. Its heading says liftoff. Both are right. The file is where the tree starts, and from then on, the tree is the page. A script can change any part of it, and the browser draws whatever the tree holds. Reload, and that tree is thrown away. The browser reads the file again, builds a new tree, and runs the script again. Look at the source of a large web app, and you'll often find a file that's almost empty. Nearly everything on screen was put there by JavaScript, in the DOM.
In one line
That's the DOM in one line: the browser turns a page's HTML into a tree of objects and draws the page from it; a script finds an element with querySelector, and whatever it changes in the tree, the page shows.
Next time
Next time, we make the page listen: events, and how a script runs a function when someone clicks a button or presses a key, with addEventListener.

