DOM Manipulation

The Document Object Model (DOM) is the browser's tree representation of a page. JavaScript can read and change it.

document<html><head><body><title><meta><h1><p>
The DOM: the browser represents the page as a tree of nodes

Selecting Elements

JavaScript
document.getElementById("title");
document.querySelector(".card");          // first match (CSS selector)
document.querySelectorAll("li");          // all matches (NodeList)

Changing Content and Style

JavaScript
const h = document.querySelector("#title");
h.textContent = "Welcome!";
h.style.color = "teal";
h.classList.add("big");

const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").append(li);
li.remove();   // delete it again

Example: To-Do List

HTML
<input id="task" placeholder="New task">
<button id="addBtn">Add</button>
<ul id="list"></ul>

<script>
document.getElementById("addBtn").addEventListener("click", () => {
    const input = document.getElementById("task");
    if (!input.value.trim()) return;
    const li = document.createElement("li");
    li.textContent = input.value;
    li.onclick = () => li.remove();          // click an item to remove it
    document.getElementById("list").append(li);
    input.value = "";
});
</script>
innerHTML vs textContentInserting user input with innerHTML can let attackers run scripts (XSS). Use textContent for plain text.
Track your progress through the JavaScript course