The DOM: your page as a tree of objects
Select elements, read and write text, create nodes and put them on the page.
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.
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 insidetextContent 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.
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 againTry it
Build a small list
Exercises
Checked in your browser · hints and solutions included
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.