The DOM: a tree you can change
The browser parses HTML into a tree of objects — the Document Object Model — and hands it to JavaScript as document. Every tag is an element with properties (textContent, className, style) and methods. Change the tree and the page updates. That is all a web framework does underneath: compute what the tree should look like, then change it.
document. Paste the code blocks below into the DevTools console (F12) on any page, or save the HTML example at the end as a file and open it. The pure-logic parts are runnable here.<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DOM demo</title>
</head>
<body>
<h1 id="title">Tasks</h1>
<ul class="tasks">
<li class="task" data-id="1">Learn the DOM</li>
<li class="task done" data-id="2">Read Module 09</li>
</ul>
<button id="add">Add</button>
<!-- scripts go last, or use defer, so the elements above exist when the code runs -->
<script type="module" src="app.js"></script>
</body>
</html>// Selecting — querySelector takes any CSS selector
const title = document.querySelector("#title") // one element (or null)
const tasks = document.querySelectorAll(".task") // a static NodeList
const list = document.querySelector("ul.tasks")
console.log(title.textContent, tasks.length, list.children.length)
// Reading and changing
title.textContent = "My tasks" // text only — safe with user input
title.style.color = "steelblue"
title.classList.add("big") // classList: add / remove / toggle / contains
console.log(tasks[0].dataset.id, tasks[1].classList.contains("done"))
// Creating and inserting
const li = document.createElement("li")
li.className = "task"
li.dataset.id = "3"
li.textContent = "Ship it"
list.append(li) // also: prepend, before, after, replaceWith
// Removing
tasks[1].remove()
// Walking the tree
console.log(li.parentElement.tagName, li.previousElementSibling.textContent, list.firstElementChild === tasks[0])
// innerHTML parses HTML — never with untrusted strings (XSS). Use textContent, or build elements.
list.insertAdjacentHTML("beforeend", "<li class=\"task\">From HTML</li>")You should see
<h1>My tasks</h1>
<ul>
<li class="task" data-id="1">Learn the DOM</li>
<li class="task done" data-id="2">Read Module 09</li>
</ul>
<script>alert(1)</script>