DOM Manipulation
The DOM is the page itself, seen as a tree of elements that JavaScript can touch. DOM stands for Document Object Model. When you change the DOM, the page updates on screen, with no reload. This is the core of JavaScript DOM manipulation and the reason pages can feel alive.
The first step is finding an element. Give an element an id attribute, and document.getElementById("demo") hands it back. The newer querySelector accepts any CSS selector, so it can find elements by class or tag too. Either way, you get an element object you can change.
If the id is misspelled or the element does not exist, getElementById returns null, and any attempt to change null throws an error that stops your script. The other common cause: the script runs before the element exists. Put your script at the end of the body, or wrap the work in a function the user triggers, and the element will be there.
Selecting elements
Every change starts with a selection. An id is a reliable address for one element, and querySelector is more flexible because it accepts any CSS selector. For collections, querySelectorAll returns a list you can loop over.
const box = document.getElementById("box");
const first = document.querySelector(".card");
const all = document.querySelectorAll("p");
Text versus markup
textContent swaps plain text safely. innerHTML parses markup, which is useful but risky if it contains user input, because it can inject unwanted code. The safe rule: prefer textContent whenever you only need text.
document.getElementById("demo").textContent = "Plain text, safe";
// innerHTML would parse HTML, so keep user input away from it
Syntax
document.getElementById("demo").textContent = "Changed by JavaScript";
document.getElementById("demo").style.color = "#d97706";
getElementById(null) Returns null, Then Crashes
Misspelled id gives null — then .textContent throws. Check spelling and put script at end.
document.getElementById("demo")?.textContent
Good to know
- The DOM is the page as a tree of elements you can change.
- getElementById returns null for a missing id, so check your spelling.
- textContent is safe for text; innerHTML parses markup.
- Put scripts at the end of the body so elements exist first.