T4 JavaScript · Lesson 8
The DOM
How a script reaches the page: the tree of elements, finding elements with getElementById and querySelector, changing text, attributes, classes and styles, making and removing elements, where a script must stand to find what it needs, and building a page's lists from data.
- say what the DOM is, and walk its tree of parents and children
- find elements with getElementById, querySelector and querySelectorAll
- change an element's text, attributes, classes and style, and say why textContent is safer than innerHTML
- make, add and remove elements
- place a script so that the elements it needs already exist, with defer or at the end of the body
- build a list on the page from an array of data
The back cover
A script that only prints to the console leaves the page as it was. The DOM is the bridge between the two: the browser's own model of the page, built as a tree of objects that a script can read and change. Change the tree, and the page on the screen changes with it.
These pages show the tree, and how to find an element in it by id or by a CSS selector. They show how to change an element's text, attributes, classes and style, and why typed text belongs in textContent. They show how to make and remove elements, and where a script must stand to find them. Last comes a list on the page, built from an array of data.
Before you start
The story: The panel that would not change
The Harbour Office's new panel should show the time of the next ferry in large brass figures. Its script works the time out correctly. Through Ottilie Sen's second lens, the one that reads a machine's diary, you can see the right answer, 4.15, written there every morning. But the panel itself still shows the dashes it was built with.
Master Hakim Verge reads the diary's first red line aloud: the script reached for the panel's figures, and found nothing there.
"A script can only change what has already been built," he says. "Find out when this one runs, and what had been built by then." Corin says that the figures are right there, on the front of the panel. "Now they are," says Master Verge.
Until now, every program in this track printed its answers in a box below the code. A web page's JavaScript does more: it reaches into the page and changes it, writing a total into a bill, adding a row to a table, hiding a message. The browser makes this possible by turning every page into a structure that scripts can read and change. This lesson is about that structure, the DOM.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| HTML elements. | <p class="price">₹40</p> | Each becomes an object a script can use. |
| Nesting. | An li inside a ul. | The DOM is a tree of parents and children. |
| CSS selectors. | .price, #total, ul li | querySelector uses the same selectors. |
| The Elements panel. | The live tree, in DevTools. | It shows every change a script makes. |
| The Console's first red line. | Cannot set properties of null | The commonest DOM error. |
| Objects and properties. | student.name | An element is an object with properties. |
| Methods. | cart.count() | Elements have methods, such as remove(). |
| Arrays and loops. | for (const item of items) | Building a list on the page from data. |
| null. | Nothing, on purpose. | What a search for a missing element gives. |
| The script element. | <script src="app.js"></script> | Where it stands decides what it can find. |
By the end of this lesson you will be able to:
- say what the DOM is, and walk its tree of parents and children;
- find elements with
getElementById,querySelectorandquerySelectorAll; - change an element's text, attributes, classes and style, and say why
textContentis safer thaninnerHTML; - make, add and remove elements;
- place a script so that the elements it needs already exist, with
deferor at the end of the body; - build a list on the page from an array of data.
How to follow this lesson
The blocks of this lesson are small web pages. Press Run to see each page under its code, and read the notes under each block: they say what the kit checked in Chrome, or what the Console showed. Keep the Elements panel of the DevTools step open while you experiment, and you can watch each change happen in the tree.
In one line
The DOM is the browser's living model of a page, which scripts read and change to change what the page shows.
The page as a tree
At a glance
A family tree starts with one person at the top and branches into children and grandchildren. Every person has one parent above and may have children below. A web page, once the browser has read it, has the same shape.
The browser turns the page's HTML into the DOM, a tree of objects: each element becomes a node, with a parent, children and siblings. The browser draws the page from this tree, so a script that changes the tree changes the page. The object document is the root, where every search starts.
Take a guess: Is the space between two tags part of the tree, or is it thrown away?
A family tree starts with one person at the top, and branches into children, grandchildren and so on. Every person has one parent above them, and may have children below. A web page, once the browser has read it, has the same shape.
The Document Object Model: the tree of objects that the browser builds from a page's HTML. Each element becomes an object, a node of the tree, which scripts can read and change. Changing a node changes what the page shows.
The browser reads the HTML once, builds the tree, and draws the page from the tree, not from the HTML text. That is why a script that changes the tree changes the page at once, while the HTML file on the server stays as it was. It is also why the Elements panel of the DevTools step shows the tree, not the file: it shows the page as it is now.
<!DOCTYPE html>
<h1>Menu</h1>
<ul>
<li>Tea</li>
<li>Vada</li>
</ul>
<script>
const list = document.querySelector("ul");
console.log(list.children.length, list.parentNode.tagName, list.firstElementChild.textContent);
</script>
The Console shows
Info 2 BODY Tea
Read the Console's line part by part. The list has 2 children, the two li elements. Its parent is the body, whose tag name the DOM writes in capitals, BODY. Its first child element holds the text Tea. Every element can be asked the same questions about its place in the tree.
| Property | Gives | Example from the block |
|---|---|---|
parentNode | the element's parent | the ul's parent is the body |
children | its child elements, in order | the ul's two li elements |
firstElementChild | its first child element | the li holding Tea |
nextElementSibling | the element just after it, with the same parent | the h1's next sibling is the ul |
tagName | its tag, in capitals | "UL" |
The object at the root of the tree, given to every script on the page. Every search for an element starts from it, as in document.querySelector(...), and document.body is the body element.
<!DOCTYPE html>
<h1>Menu</h1>
<ul>
<li>Tea</li>
<li>Vada</li>
</ul>
<script>
const heading = document.querySelector("h1");
console.log(heading.nextElementSibling.tagName, document.body.contains(heading));
</script>
The Console shows
Info UL true
The h1's next sibling is the ul, and document.body.contains(heading) confirms that the heading is somewhere inside the body. Elements are objects of the objects lesson: they have properties, such as tagName, and methods, such as contains.
Worked example 1
A school notice page has a heading, Notices, and below it a list of three notices. Use the tree to print how many notices there are and the text of the last one, starting from the heading.
What we have: a heading followed by a list of three items
What we need: the number of items and the last item's text
The plan: the list is the heading's next sibling; its children are the notices
<!DOCTYPE html>
<h2>Notices</h2>
<ol>
<li>Sports day on Friday</li>
<li>Library closed on Monday</li>
<li>Fees due by the 10th</li>
</ol>
<script>
const list = document.querySelector("h2").nextElementSibling;
console.log(list.children.length, list.lastElementChild.textContent);
</script>
The Console shows
Info 3 Fees due by the 10th
There are 3 notices, and the last reads Fees due by the 10th.
Check: the Console line shows both answers, read from the tree.
A path that fails: counting with list.childNodes.length. childNodes includes the pieces of text between the tags, such as line breaks, so it gives a larger number than the 3 notices. children holds only the elements.
When you are stuck: you cannot find your way around the tree
Open the Elements panel and look at the live tree: it is the one your script works on.
Use parentNode to go up, children to go down, and nextElementSibling to go across.
Print an element's tagName to check which element you are holding.
Remember that childNodes counts text between tags as well; children counts elements only.
Your turn
In a page with <ul><li>A</li><li>B</li></ul>, what is the first li's parentNode, and how many children does the ul have?Tap to reveal
- The li sits inside the ul, so its parent is the ul.
- The ul holds two li elements.
The parent is the ul, and it has 2 children.
Why does a script's change appear on the page at once, while the HTML file does not change?Tap to reveal
- The browser draws the page from the DOM tree it built.
- The script changes the tree, not the file.
Because the page is drawn from the tree, which the script changed.
What does document.body hold?Tap to reveal
- document is the root of the tree.
- Its body property is the page's body element.
The page's body element.
Did you know?
Spaces are nodes too
The spaces and line breaks between tags are not thrown away. MDN explains that whitespace between HTML tags becomes text nodes in the DOM, and javascript.info adds that spaces and newlines are valid characters, like letters and digits. So a list written on five lines holds text nodes of spaces between its items. A script that walks every node of the tree meets them too.
Why it fits here: It explains a surprise in this topic's tree: between the element nodes sit text nodes made only of spaces and line breaks.
Sources: MDN: How whitespace is handled by HTML, CSS, and in the DOM; javascript.info: DOM tree
How big is too big
A tree can grow too big. Lighthouse, Chrome's tool for grading pages, warns when the body element holds more than about 800 nodes, and reports an error above about 1400. Its guide explains the cost: as people and scripts use a page, the browser must keep working out the position and style of its nodes, and a large tree with complicated style rules can badly slow the page down.
Why it fits here: It puts a number on this topic's tree: every element is a node the browser must place and style, so a page should not hold thousands it does not need.
In one line
The browser turns a page's HTML into the DOM, a tree of element objects with parents, children and siblings, and draws the page from it. A script that changes the tree changes the page; document is the root that every search starts from.
Finding elements
At a glance
Before a script can change an element, it must get hold of it, as you must find a book on a shelf before you can open it. There are three common ways to look.
The method getElementById finds the one element with a given id, written with no # in front. The method querySelector takes any CSS selector and finds the first match, and querySelectorAll finds every match as a NodeList. A search that finds nothing gives null, and using that null brings the error Cannot set properties of null.
Take a guess: If two elements on a page share one id, which one does getElementById give back?
Before a script can change an element, it must get hold of it, as you must find a book on a shelf before you can open it. There are three common ways to look.
| Method | Finds | Gives back |
|---|---|---|
document.getElementById("price") | the element with that id | the element, or null |
document.querySelector(".note") | the first element that matches a CSS selector | the element, or null |
document.querySelectorAll(".note") | every element that matches | a NodeList, which may be empty |
<!DOCTYPE html>
<p id="price">₹40</p>
<p class="note">Fresh today</p>
<p class="note">Sold out by noon</p>
<script>
console.log(document.getElementById("price").textContent, document.querySelector(".note").textContent, document.querySelectorAll(".note").length, document.querySelector(".missing"));
</script>
The Console shows
Info ₹40 Fresh today 2 null
The method getElementById takes the id with no # in front. The method querySelector takes any CSS selector, exactly as a stylesheet writes it, # and . included, and gives the first match: there are two notes, and it gave the first. The method querySelectorAll gives all of them; its length is 2. A selector that matches nothing gives null, the value the values lesson called "nothing, on purpose".
The null trap
Using the null from a failed search as if it were an element is the most common error in all of browser JavaScript, and the one in the story:
<!DOCTYPE html>
<p id="price">₹40</p>
<p class="note">Fresh today</p>
<p class="note">Sold out by noon</p>
<script>
document.querySelector(".cost").textContent = "₹60";
console.log("never printed");
</script>
The Console shows
Error Uncaught TypeError: Cannot set properties of null (setting 'textContent')
There is no element with the class cost, so querySelector gave null, and null has no properties to set. When you see this message, check the selector against the page, and check that the element exists at the moment the script runs, which the scripts section of this lesson explains.
Many elements: a NodeList
querySelectorAll gives a NodeList: a list of elements that looks like an array but is not one. It has a length and a forEach, and works with for...of, but it has no map or filter. To use those, turn it into an array first with Array.from(...):
<!DOCTYPE html>
<p id="price">₹40</p>
<p class="note">Fresh today</p>
<p class="note">Sold out by noon</p>
<script>
const notes = document.querySelectorAll(".note");
console.log(Array.isArray(notes), typeof notes.map);
const texts = Array.from(notes).map((p) => p.textContent);
console.log(texts.join(" | "));
</script>
The Console shows
Info false undefined
Info Fresh today | Sold out by noon
A search can also start from an element instead of from the whole document, to look only inside it: menu.querySelector("li") finds the first li inside menu. This keeps a script from picking up a matching element from some other part of the page.
Worked example 2
A canteen's page lists dishes, each in an li with the class dish, and marks the ones that are sold out with a second class, sold-out. Print how many dishes there are and the names of those sold out.
What we have: a list of dishes, some with the class sold-out
What we need: the count of dishes and the names that are sold out
The plan: querySelectorAll with a class selector for all dishes, and a selector with both classes for the sold-out ones
<!DOCTYPE html>
<ul>
<li class="dish">Idli</li>
<li class="dish sold-out">Dosa</li>
<li class="dish">Upma</li>
<li class="dish sold-out">Poha</li>
</ul>
<script>
const all = document.querySelectorAll(".dish");
const gone = document.querySelectorAll(".dish.sold-out");
console.log(all.length, Array.from(gone).map((li) => li.textContent).join(", "));
</script>
The Console shows
Info 4 Dosa, Poha
There are 4 dishes, and Dosa and Poha are sold out.
Check: two of the four items carry the second class.
A path that fails: writing ".dish .sold-out" with a space. That means a sold-out element inside a dish, which matches nothing here, so the list of sold-out dishes is empty.
When you are stuck: a search gives null, or nothing
Print the search on its own: console.log(document.querySelector(".cost"));.
Compare the selector with the page in the Elements panel: a class needs a dot, an id a #, except in getElementById.
Check that the script runs after the element exists.
For many elements, use querySelectorAll, and Array.from before map or filter.
Your turn
What does document.querySelector("p") give on a page with three paragraphs?Tap to reveal
- querySelector gives the first match only.
- So it gives the first paragraph.
The first paragraph.
Why does document.querySelectorAll("li").map(...) fail?Tap to reveal
- querySelectorAll gives a NodeList.
- A NodeList has forEach but no map.
- Array.from turns it into an array, which has map.
A NodeList has no map; use Array.from(list).map(...).
Which call finds the element with id total: getElementById("#total") or getElementById("total")?Tap to reveal
- getElementById takes the id itself, with no #.
- The # belongs to CSS selectors, as in querySelector("#total").
getElementById("total").
Did you know?
Live lists and frozen lists
Some lists of elements keep themselves up to date. The DOM standard says a collection can be live or static, and is live unless stated otherwise: it follows the page as the page changes. MDN notes that querySelectorAll is the only method that returns a static NodeList, a snapshot taken at the moment of the call. So an element added later joins a live list, but never the snapshot.
Why it fits here: It explains why a list from this topic's querySelectorAll does not grow when the page later gains a matching element.
Sources: WHATWG: DOM Standard; MDN: NodeList
Two elements, one id
An id is meant to belong to one element: the HTML standard says it must be unique among all the ids in its tree. Pages still break the rule, and the DOM standard says what happens then. The method getElementById returns the first matching element in tree order, which is a preorder, depth-first walk: the order the tags appear in the page. The second element is never found by its id.
Why it fits here: It answers this topic's question about ids: a repeated id is a bug in the page, and the search quietly gives only the first.
Sources: WHATWG: HTML Standard, the id attribute; WHATWG: DOM Standard
In one line
getElementById finds by id, querySelector finds the first match of a CSS selector, and querySelectorAll finds every match as a NodeList. A search that finds nothing gives null, and using that null is the error Cannot set properties of null.
Changing what an element shows
At a glance
Once a script holds an element, it can change four things about it: its text, its attributes, its classes and its style. Each is a property or a method of the element object.
The property textContent sets plain text, and innerHTML reads its string as markup, so text a person typed belongs in textContent. The method setAttribute changes an attribute, classList adds, removes and toggles classes, and style sets inline styles with camelCase names, such as backgroundColor. The page shows each change straight away.
Take a guess: If a script puts a script tag into innerHTML, does that script run?
Once a script holds an element, it can change four things about it: its text, its attributes, its classes and its style. Each is a property or a method of the element object.
Text: textContent
textContent is the element's text. Reading it gives the text; assigning to it replaces everything inside the element with the new text:
<!DOCTYPE html>
<p id="time">--.--</p>
<script>
const time = document.getElementById("time");
time.textContent = "4.15";
</script>
Checked in Chrome
- the panel now shows 4.15 instead of its dashes
Markup: innerHTML, and why to be careful
innerHTML is the element's contents written as HTML. Assigning to it makes the browser read the string as HTML, so tags in it become real elements. textContent, by contrast, puts the string in as plain text, tags and all:
<!DOCTYPE html>
<p id="a"></p>
<p id="b"></p>
<script>
const name = "<b>Asha</b>";
document.getElementById("a").innerHTML = name;
document.getElementById("b").textContent = name;
</script>
Checked in Chrome
- with innerHTML, the tags became a real bold element
- with textContent, the tags are shown as plain text, and no element was made
That difference matters whenever the text comes from a person. If a user's name, a review or a search is put into a page with innerHTML, the user can put tags into the page, and with some tags, a script of their own, which then runs for every visitor. This is called cross-site scripting, or XSS, and MDN's page on innerHTML warns about it. The rule that prevents it: put text into a page with textContent, and use innerHTML only for markup you wrote yourself. The security step of this path returns to it.
Attributes
An element's attributes, such as an image's src or a link's href, can be read and set with getAttribute and setAttribute. Common attributes also appear as properties of the same name:
<!DOCTYPE html>
<a id="map" href="/pune">Map</a>
<script>
const link = document.getElementById("map");
link.setAttribute("href", "/nagpur");
link.title = "Open the map of Nagpur";
console.log(link.getAttribute("href"), link.title);
</script>
The Console shows
Info /nagpur Open the map of Nagpur
Classes: classList
The cleanest way to change how an element looks is to change its classes, and let the stylesheet say what each class looks like. classList has a method for each job:
| Method | What it does |
|---|---|
classList.add("x") | adds the class x |
classList.remove("x") | removes it |
classList.toggle("x") | adds it if it is missing, removes it if it is there |
classList.contains("x") | true if the element has it |
<!DOCTYPE html>
<style>.late { color: rgb(200, 0, 0); }</style>
<p id="ferry">4.15 ferry</p>
<script>
const ferry = document.getElementById("ferry");
ferry.classList.add("late");
console.log(ferry.classList.contains("late"), ferry.className);
</script>
Checked in Chrome
- the stylesheet's rule for late now colours the line red
The Console shows
Info true late
Style
An element's style property sets inline styles one at a time. CSS names with hyphens are written in camelCase, so background-color becomes backgroundColor:
<!DOCTYPE html>
<p id="note">Closed today</p>
<script>
const note = document.getElementById("note");
note.style.backgroundColor = "rgb(255, 240, 200)";
note.style.fontWeight = "700";
</script>
Checked in Chrome
- the note now has a pale yellow background
- and bold text
Inline styles beat the stylesheet, as the CSS step showed, and they scatter the look of a page through its scripts. Prefer classList for anything more than a one-off change.
Worked example 3
A results page shows each student's status. Asha's line should read Passed and turn green when her marks, 412, are 300 or more. Write the script, using a class for the colour.
What we have: a line for Asha, her marks, and a pass mark of 300
What we need: the text Passed, and the class pass on the line
The plan: find the line, decide with an if, then set textContent and add the class
<!DOCTYPE html>
<style>.pass { color: rgb(0, 128, 0); }</style>
<p id="asha">Asha: waiting</p>
<script>
const marks = 412;
const line = document.getElementById("asha");
if (marks >= 300) {
line.textContent = "Asha: Passed";
line.classList.add("pass");
}
</script>
Checked in Chrome
- the line reads Asha: Passed
- and the pass class colours it green
The line reads Asha: Passed, in green.
Check: 412 is at least 300, so the if's block ran.
A path that fails: setting line.style.color = "green" in the script. It works, but the colour now lives in the script; when the school changes its colours, someone must find every script that sets one.
When you are stuck: a change does not show
Check that you assigned the property: el.textContent = ..., not only read it.
Look at the element in the Elements panel to see what the script really changed.
If tags appear as text, you used textContent; if text turned into elements, you used innerHTML.
For style properties, write CSS names in camelCase: backgroundColor, fontSize.
Your turn
What does a page show after el.textContent = "<i>hi</i>";?Tap to reveal
- textContent puts the string in as plain text.
- So the tags are shown, as characters, and nothing is made italic.
It shows <i>hi</i> as plain text.
Why is textContent the safer way to show a user's review on a page?Tap to reveal
- innerHTML reads the review as HTML, so tags in it become real elements, and could run a script.
- textContent never makes elements from the text.
Because textContent never turns the text into markup, so a user cannot inject tags.
Write the line that switches the class dark on and off on the body.Tap to reveal
- toggle adds a class that is missing and removes one that is there.
document.body.classList.toggle("dark");
Did you know?
Script tags that never run
A script tag put in through innerHTML does nothing: the HTML standard says scripts inserted that way do not execute at all. That does not make innerHTML safe. MDN calls it probably the most common route for cross-site scripting attacks, because HTML has many other ways to run code. Its own example is an image with a broken address, whose error handler runs the attacker's code.
Why it fits here: It is the reason behind this topic's rule: typed text goes into textContent, because innerHTML can run code without any script tag.
Sources: WHATWG: HTML Standard, the script element; MDN: Element.innerHTML
Why float was once cssFloat
Most CSS names change only to camelCase in JavaScript, but float got a new name. In 1999 the third edition of the JavaScript standard listed float among its future reserved words, and the W3C's style interface of November 2000 named the property cssFloat. MDN compares it with the class attribute, read as className. Modern browsers accept style.float as well, and today's standard still keeps cssFloat.
Why it fits here: It adds the one odd case to this topic's camelCase rule: the float property was once reached only as cssFloat.
Sources: ECMAScript Language Specification, 3rd edition (December 1999); W3C: Document Object Model (DOM) Level 2 Style Specification; MDN: float; CSS Object Model (CSSOM)
In one line
textContent sets an element's text, innerHTML its markup; use textContent for anything a person typed, or they can inject tags. setAttribute changes attributes, classList adds, removes and toggles classes, and style sets inline styles in camelCase.
Making and removing elements
At a glance
A carpenter builds a new shelf first and then fixes it to the wall. A script makes new parts of a page in the same two steps: first make the element, then put it somewhere in the tree.
The method document.createElement makes an element that is not yet on the page. After its text and classes are set, append puts it at the end of a parent and prepend at the start. The method remove takes an element out again, as the older parentNode.removeChild does.
Take a guess: If an element already on the page is appended somewhere else, is it copied or moved?
A script can also build new parts of a page, as a carpenter builds a new shelf and then fixes it to the wall. The two steps are separate: first make the element, then put it somewhere in the tree. Until the second step, the new element exists, but is not on the page.
A method of document that makes a new element of a given tag, not yet in the page: document.createElement("li").
<!DOCTYPE html>
<ul id="cart">
<li>Rice</li>
</ul>
<script>
const item = document.createElement("li");
item.textContent = "Dal";
console.log(document.querySelectorAll("#cart li").length);
document.getElementById("cart").append(item);
console.log(document.querySelectorAll("#cart li").length);
</script>
Checked in Chrome
- Dal is now the last item of the cart
The Console shows
Info 1
Info 2
After createElement and setting its text, the new li existed, but the cart still had 1 item, as the first Console line shows. append put it at the end of the cart, and the count became 2. prepend puts an element at the start instead. You will also meet the older appendChild, which does the same as append for a single element.
Removing an element
An element can remove itself with remove(). Older code asks the parent to do it, with parent.removeChild(child), often written child.parentNode.removeChild(child):
<!DOCTYPE html>
<ul id="cart">
<li>Rice</li>
<li id="dal">Dal</li>
<li id="oil">Oil</li>
</ul>
<script>
document.getElementById("dal").remove();
const oil = document.getElementById("oil");
oil.parentNode.removeChild(oil);
console.log(document.querySelectorAll("#cart li").length);
</script>
The Console shows
Info 1
To empty an element of everything inside it, set its textContent to the empty string, or call replaceChildren() with nothing in the brackets.
Worked example 4
A delivery app shows a list of today's orders. A new order, for Meera, arrives. Add it at the top of the list, styled with the class new, and remove the order that was cancelled, Ravi's.
What we have: a list with two orders, Asha's and Ravi's
What we need: Meera first, then Asha, with Ravi's gone
The plan: make an li for Meera, give it its text and class, prepend it; then remove Ravi's li
<!DOCTYPE html>
<ul id="orders">
<li>Asha</li>
<li id="ravi">Ravi</li>
</ul>
<script>
const li = document.createElement("li");
li.textContent = "Meera";
li.classList.add("new");
const list = document.getElementById("orders");
list.prepend(li);
document.getElementById("ravi").remove();
</script>
Checked in Chrome
- the list now reads Meera, then Asha
- and Meera's order carries the class new
The list reads Meera, Asha.
Check: two items: the new one at the top, and Ravi's gone.
A path that fails: setting list.innerHTML += "<li>Meera</li>". It works for a name you wrote, but it rebuilds the whole list from text each time, and a customer's name containing a tag would become markup.
When you are stuck: a new element does not appear
Check that you added it to the page with append or prepend; createElement alone does not.
Check that the parent you appended to is the one on the page: print it.
If an element appears twice in the wrong place, remember that appending an element that is already on the page moves it.
Look in the Elements panel to see where it really went.
Your turn
After const p = document.createElement("p");, is the new paragraph on the page?Tap to reveal
- createElement makes the element, but puts it nowhere.
- It appears only after something like document.body.append(p).
No, not until it is appended.
Write the line that removes the element with id banner.Tap to reveal
- Find it, then call remove on it.
document.getElementById("banner").remove();
What is the difference between append and prepend?Tap to reveal
- append adds at the end of the parent's children.
- prepend adds at the start.
append adds last, prepend adds first.
Did you know?
One element, one place
An element can stand in only one place in the tree. MDN notes that appending an element that is already in the document moves it from its current position to the new one. The DOM standard's steps show why: if the node already has a parent, it is removed from that parent first. So append never makes a copy; to show the same thing twice, a script must make a second element.
Why it fits here: It answers this topic's question about appending an element already on the page: it moves, and its old place is left empty.
Sources: MDN: Node.appendChild(); WHATWG: DOM Standard
A move that keeps its state
Moving an element the usual way removes it and puts it back, and that can reset it. MDN lists what would be reset: animations, an iframe's loading state, focus and more. Chrome 133 added a method, moveBefore(), that moves an element without losing that state. MDN marks it as limited availability for now: it does not yet work in some of the most widely used browsers.
Why it fits here: It shows a limit of this topic's append: a moved element can lose its focus or animation, which a newer method avoids.
Sources: MDN: Element.moveBefore(); Chrome for Developers: Preserve state during DOM mutations with moveBefore()
In one line
createElement makes a new element that is not yet on the page; set its text and classes, then put it in with append or prepend. remove() takes an element out, as the older parentNode.removeChild(...) does.
Where a script stands
At a glance
The browser reads a page from the top down, building the tree as it goes. When it meets a script, it stops, runs the script, and only then carries on reading.
So a script can find only the elements above it, and a search for anything below gives null. The cure is to put page scripts at the end of the body, or to load them with defer, which waits until the whole page has been read. The attribute async does not wait.
Take a guess: Does a script of type module need defer to find the elements below it?
The browser reads a page from the top down, building the tree as it goes. When it meets a script, it stops, runs the script, and only then carries on reading. So a script can find only the elements that come before it in the page. This is the trap of the story: the script stood at the top, and ran before the panel was built.
<!DOCTYPE html>
<head>
<script>
document.querySelector("#time").textContent = "4.15";
</script>
</head>
<body>
<p id="time">--.--</p>
</body>
Checked in Chrome
- the panel still shows its dashes, as the script ran before it existed
The Console shows
Error Uncaught TypeError: Cannot set properties of null (setting 'textContent')
When the script ran, there was no #time yet, so querySelector gave null. The same script at the end of the body finds the panel, because by then the browser has built everything above it:
<!DOCTYPE html>
<body>
<p id="time">--.--</p>
<script>
document.querySelector("#time").textContent = "4.15";
</script>
</body>
Checked in Chrome
- the panel shows 4.15
Script files, and defer
Real pages keep their JavaScript in files, loaded with <script src="board.js"></script>. Such a script is often placed in the head, so that the browser starts fetching it early. Placed there plainly, it has the same problem. The kit served each of the next two pages, with a file board.js beside them, from a small real server, and read Chrome's Console. The first page loads the file in the head:
<!DOCTYPE html>
<head>
<script src="board.js"></script>
</head>
<body>
<p id="time">--.--</p>
</body>
The Console shows
Error Uncaught TypeError: Cannot set properties of null (setting 'textContent')
The fix is one word. A script with the defer attribute is fetched while the browser goes on building the page, and run only once the whole page has been read:
<!DOCTYPE html>
<head>
<script src="board.js" defer></script>
</head>
<body>
<p id="time">--.--</p>
</body>
The Console shows
Info board shows 4.15
| How the script is loaded | When it runs | Can it find the page's elements? |
|---|---|---|
<script> in the head | at once, before the body is read | no |
<script> at the end of the body | once everything above it is read | yes |
<script src="..." defer> | after the whole page is read, in page order | yes |
<script src="..." async> | as soon as the file arrives, whenever that is | not reliably |
async suits scripts that do not touch the page's elements, such as some analytics scripts, because nobody can say whether the page will be read by the time the file arrives. For a script that works on the page, use defer, or put the script at the end of the body. Modules, which the modern JavaScript step teaches, are deferred without the word.
A script can also wait for the page in a third way, by asking the browser to call a function once the page has been read, with the event DOMContentLoaded. Events are the subject of the next lesson.
Worked example 5
A school's notice page loads notices.js from its head, and the script writes today's date into a span with the id today. Teachers report that the date never appears. Find the cause and the smallest fix.
What we have: a script file loaded in the head, and a span further down
What we need: the date in the span
The plan: a script in the head runs before the body exists; defer makes it wait for the whole page
- The script runs when the browser reaches it, in the head, before the span has been built, so querySelector gives null.
- Adding defer,
<script src="notices.js" defer></script>, makes it run after the whole page has been read, as the served page above showed.
The smallest fix is defer on the script tag.
Check: the Console's red line, Cannot set properties of null, disappears, and the span is filled.
Another way: move the script tag to the end of the body. It works as well, but defer keeps all the page's scripts together in the head, where the browser can start fetching them early.
When you are stuck: a script cannot find an element that is plainly on the page
Look at where the script stands: if it comes before the element, it ran first.
For a script file, add defer; for an inline script, move it to the end of the body.
Do not use async for a script that works on the page's elements.
The Console's red line, Cannot set properties of null, usually means exactly this.
Your turn
Why can a script in the head not find an element in the body, when the script has no defer?Tap to reveal
- The browser runs a script as soon as it reaches it.
- In the head, the body has not been read, so its elements do not exist yet.
Because the element is built after the script runs.
What does defer change?Tap to reveal
- The file is fetched while the page is read.
- It runs only after the whole page has been read.
It makes the script wait until the page has been read.
Should a script that fills a table use async?Tap to reveal
- async runs as soon as the file arrives, which may be before the table exists.
- defer, or the end of the body, is safe.
No: use defer.
Did you know?
Modules wait without being asked
A script of type module waits by itself. The HTML standard says a module script is fetched while the page is read, and run when the page has finished parsing, the same as a defer script. It adds that the defer attribute has no effect on module scripts. So a module script at the top of the page can already find every element below it.
Why it fits here: It adds a third way to this topic's two: a module script waits for the whole page, like defer, without being told.
The moment the tree is ready
Pages have an event for the moment the tree is complete: DOMContentLoaded. The HTML standard fires it at the document when parsing ends. MDN notes that it comes after deferred scripts, but does not wait for images, subframes or async scripts. A script that cannot use defer can listen for this event instead, and start its work only when every element exists.
Why it fits here: It names the moment this topic's defer scripts wait for: the tree is complete, though pictures may still be loading.
Sources: WHATWG: HTML Standard, parsing HTML documents; MDN: Document: DOMContentLoaded event
In one line
The browser runs a script as soon as it reaches it, so a script can find only the elements above it. Put page scripts at the end of the body, or load them with defer, which waits until the whole page has been read; async does not wait.
Building a page from data
At a glance
Most of what a real page shows comes from data, not from its HTML: a shop's products, a school's results, a train's stops. The data arrives as an array of objects, and a script turns each object into elements.
The loop is always the same: create an element, fill it with textContent, append it. To show new data, empty the parent with replaceChildren() and build again. The HTML can hold just an empty list; everything inside it comes from the data. Here the arrays, objects, loops and DOM of this track meet.
Take a guess: If a list is rebuilt without emptying it first, what does the page show?
Most of what a real page shows comes from data, not from its HTML: a shop's products, a school's results, a train's stops. The data arrives as an array of objects, and a script turns each object into elements. Here the arrays, objects, loops and DOM of this track meet.
<!DOCTYPE html>
<ul id="menu"></ul>
<script>
const dishes = [
{ name: "Idli", price: 40 },
{ name: "Dosa", price: 60 },
{ name: "Vada", price: 30 },
];
const menu = document.getElementById("menu");
for (const dish of dishes) {
const li = document.createElement("li");
li.textContent = `${dish.name}: ₹${dish.price}`;
menu.append(li);
}
</script>
Checked in Chrome
- the menu has one item for each dish
- the first reads Idli: ₹40
For each dish, the loop makes an li, sets its text from the object's properties, and appends it. The HTML held only an empty ul; everything inside it came from the data. Add a fourth dish to the array, and the menu grows by one, with no change to the HTML.
Updating a list
When the data changes, the simplest way to keep the page right is to empty the list and build it again from the new data. replaceChildren() with no arguments empties an element. A function that does the whole job can then be called whenever the data changes:
<!DOCTYPE html>
<ul id="menu"></ul>
<script>
function render(list, dishes) {
list.replaceChildren();
for (const dish of dishes) {
const li = document.createElement("li");
li.textContent = dish.name;
list.append(li);
}
}
const menu = document.getElementById("menu");
render(menu, [{ name: "Idli" }, { name: "Dosa" }]);
render(menu, [{ name: "Poha" }]);
</script>
Checked in Chrome
- after the second render, the menu holds only Poha
Without the replaceChildren line, the second render would add Poha below Idli and Dosa, and the menu would grow with every update. A function like render, which draws a part of the page from data, is the seed of the idea behind React, which the React step of this path teaches.
Worked example 6
A results portal receives an array of results and must show a table row for each student, with the name, the marks and, for marks of 400 or more, the class good on the row. The results are Asha 412, Ravi 389 and Meera 455.
What we have: an array of three result objects, and an empty table body
What we need: three rows, two of them with the class good
The plan: loop over the results; for each, make a tr with two td cells, set their text, add the class when the marks are high, and append the row
<!DOCTYPE html>
<table><tbody id="rows"></tbody></table>
<script>
const results = [
{ name: "Asha", marks: 412 },
{ name: "Ravi", marks: 389 },
{ name: "Meera", marks: 455 },
];
const rows = document.getElementById("rows");
for (const r of results) {
const tr = document.createElement("tr");
const name = document.createElement("td");
const marks = document.createElement("td");
name.textContent = r.name;
marks.textContent = r.marks;
tr.append(name, marks);
if (r.marks >= 400) tr.classList.add("good");
rows.append(tr);
}
</script>
Checked in Chrome
- the table has three rows
- two of them, Asha's and Meera's, carry the class good
- the first cell reads Asha
tr.append(name, marks) adds both cells in order.Three rows, with Asha and Meera marked good.
Check: 412 and 455 are at least 400; 389 is not.
A path that fails: building each row as a string, rows.innerHTML += `<tr><td>${r.name}</td>...`. It looks shorter, but a name containing a tag would become markup, and the whole table is rebuilt from text on every pass of the loop.
When you are stuck: a list on the page is wrong
If items repeat after an update, empty the list before building it again.
If nothing appears, check that each new element is appended, and to the right parent.
Print the data before the loop, to check that it holds what you expect.
Build text with textContent, not innerHTML, whenever it comes from data.
Your turn
A render function is called twice with the same three dishes, and the menu shows six. Why?Tap to reveal
- Each call appends three items.
- Nothing emptied the list between the calls.
Because the list was not emptied first; add list.replaceChildren();.
Which is safer for a dish's name from a server: li.textContent = dish.name or li.innerHTML = dish.name?Tap to reveal
- textContent never turns text into markup.
- innerHTML would read any tags in the name as HTML.
li.textContent = dish.name.
What does tr.append(a, b) do?Tap to reveal
- append can take several nodes.
- It adds them at the end, in the order given.
It adds a, then b, at the end of the row.
Did you know?
A billion comparisons
Rebuilding a whole list is the plain way; libraries such as React try to change only what differs. React's own guide explains that the best general methods for comparing two trees take time on the order of n3, so 1000 elements would need about one billion comparisons. React uses a quicker rule of thumb instead, and asks for a key on each list item so it can match old items with new ones.
Why it fits here: It shows how big libraries avoid this topic's rebuild from scratch: they compare the new list with the old and change only the differences.
Sources: React (legacy docs): Reconciliation; React: Rendering Lists
Emptying in one call
An element can be emptied in one call. The DOM standard's replaceChildren() swaps all of an element's children for the nodes it is given, so called with nothing, it leaves the element empty. MDN calls it a very convenient way to empty a node, and shows it working across browsers since October 2020, so code older than that empties its lists in other ways.
Why it fits here: It is the tool this topic uses to update a list: one call clears the old items before the loop builds the new ones.
Sources: WHATWG: DOM Standard; MDN: Element.replaceChildren()
In one line
Pages show data by turning each item of an array into elements in a loop: create, fill with textContent, append. To update, empty the element with replaceChildren() and build again from the new data.
Where it is used
Every interactive web page uses the DOM. Here is where each idea of this lesson shows up in real work.
| What you learned | Where it is used | A real example |
|---|---|---|
| the DOM tree | every page a browser shows | the Elements panel showing a shop page's live structure |
| querySelector and querySelectorAll | finding the parts a script works on | finding every price on a page to convert it to another currency |
| textContent | putting text on a page | writing the total into a bill |
| innerHTML, with care | markup written by the page's own authors | a help box filled with a ready-made paragraph |
| classList | changing the look through the stylesheet | marking a late train red; switching a dark theme on |
| createElement and append | adding to a page | a new chat message added to the bottom of a conversation |
| remove | taking things away | a cancelled order disappearing from the list |
| defer | loading a page's scripts | a site that loads all its scripts in the head with defer |
| building from data | lists, tables and grids | a product grid drawn from an array the server sent |
Mistakes and debugging
These are the slips that people meet most often with the DOM. The notes under each page say what the kit measured in Chrome.
1. A selector that matches nothing
<!DOCTYPE html>
<p class="price"></p>
<script>
document.querySelector(".cost").textContent = "₹60";
</script>
The Console shows
Error Uncaught TypeError: Cannot set properties of null (setting 'textContent')
The fix: make the selector match the page: ".price". Print the search on its own to see the null.
2. A script that runs before the element exists
<!DOCTYPE html>
<head>
<script>
document.querySelector("#time").textContent = "4.15";
</script>
</head>
<body>
<p id="time">--.--</p>
</body>
The Console shows
Error Uncaught TypeError: Cannot set properties of null (setting 'textContent')
The fix: move the script to the end of the body, or load the file with defer.
3. map on a NodeList
<!DOCTYPE html>
<li>a</li><li>b</li>
<script>
const items = document.querySelectorAll("li");
items.map((li) => li.textContent);
</script>
The Console shows
Error Uncaught TypeError: items.map is not a function
The fix: Array.from(items).map(...).
4. A # in getElementById
<!DOCTYPE html>
<p id="total"></p>
<script>
document.getElementById("#total").textContent = "₹465";
</script>
The Console shows
Error Uncaught TypeError: Cannot set properties of null (setting 'textContent')
The fix: getElementById takes the id alone: getElementById("total"); querySelector is the one that takes "#total".
5. A user's text put in with innerHTML
<!DOCTYPE html>
<p id="review"></p>
<script>
const typed = "<b>Great</b> food";
document.getElementById("review").innerHTML = typed;
</script>
Checked in Chrome
- the typed tags became a real element: a user can put markup into the page
The fix: textContent for anything a person typed.
6. A new element never appended
<!DOCTYPE html>
<ul id="cart"></ul>
<script>
const li = document.createElement("li");
li.textContent = "Dal";
</script>
Checked in Chrome
- the cart is still empty: the li was made but never put on the page
The fix: document.getElementById("cart").append(li);.
The debugging corner: compare the tree with the script
For any DOM bug, open the Elements panel and look at the live tree at the moment the script runs. Is the element there? Does it have the id or class the script asks for? A breakpoint on the script's first line in the Sources panel stops the page at exactly that moment, so you can see what had been built by then.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
<!DOCTYPE html>
<style>.late { color: rgb(200, 0, 0); }</style>
<h1>Ferries</h1>
<p id="next">--.--</p>
<ul id="list"></ul>
<script>
// find: getElementById, querySelector (first match), querySelectorAll (all)
const next = document.getElementById("next");
const heading = document.querySelector("h1");
// change: textContent (safe), classList, style, setAttribute
next.textContent = "4.15";
next.classList.add("late");
heading.setAttribute("title", "Harbour ferries");
// build from data: create, fill, append
for (const time of ["4.15", "5.30"]) {
const li = document.createElement("li");
li.textContent = time;
document.getElementById("list").append(li);
}
console.log(document.querySelectorAll("#list li").length, heading.title);
</script>
Checked in Chrome
- the panel shows 4.15
- in red, from the class late
- and the list has both ferries
The Console shows
Info 2 Harbour ferries
| When you see | It means | Look at |
|---|---|---|
Cannot set properties of null | the search found nothing, or ran too early | the selector; where the script stands |
... .map is not a function | a NodeList, which has no map | Array.from(...) |
| tags shown as text | textContent was used for markup | textContent for text, innerHTML only for your own markup |
| text turned into elements | innerHTML was used for text | textContent |
| a new element missing | it was never appended | append or prepend |
| items repeated after an update | the list was not emptied | replaceChildren() |
The story: Built first, then changed
You find that the script stood at the very top of the panel's plan, so it ran before the figures were made. You move it, and tell it to wait until the whole panel is built. Then it reaches for the figures by their name, finds them, and writes the time into them.
The dashes click over to 4.15. When the ferry leaves, they change again, by themselves.
Master Verge watches a passenger read the panel. "Now the script can reach the panel," he says. "Next, the panel must answer when a passenger touches it."
Reagents gathered: DOM, querySelector, textContent, createElement, defer, classList.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- HTML Living Standard (WHATWG) (CC BY 4.0: "Copyright WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License" (its acknowledgements page, read 2026-10-26); reused with credit)