ILILCode
HomeJavaScriptThe browser

The DOM: your page as a tree of objects

Select elements, read and write text, create nodes and put them on the page.

Lesson 10 of 23 in JavaScript11 min1 exercise

When the browser loads HTML it builds a DOM — a tree of objects you can read and change from JavaScript. Every element is a node with properties like textContent, classList and children.

Selecting elements
document.getElementById("app");        // one element by id
document.querySelector(".card");       // first match for a CSS selector
document.querySelectorAll("li");       // a NodeList of every match

const app = document.querySelector("#app");
app.textContent;                       // everything as text
app.innerHTML;                         // the HTML inside

textContent reads or writes plain text — the browser escapes it for you, so it is safe for user input. innerHTML parses a string as HTML. It is convenient and dangerous: never send user input through it.

Creating and inserting nodes
const item = document.createElement("li");
item.textContent = "Write a loop";
item.classList.add("done");
item.dataset.id = "42";        // becomes data-id="42"

const list = document.querySelector("#list");
list.append(item);             // add as the last child
list.prepend(item);            // add as the first child
item.remove();                 // take it out again

Try it

Build a small list

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Render a reading list

Given the books array, render a <ul id="library"> inside #app with one <li> per book. Each item shows the title and the year in parentheses: Eloquent JavaScript (2018).

Build the elements with createElement instead of gluing HTML strings.

exercise.js
console · run your code or check the answer