Open original
Info
Demo 3.8

The Document Object Model (DOM)

Files in this demo

├─ index.html
└─ script.js

When a browser loads your HTML, it builds a live model of the page in memory. That model is the DOM, and JavaScript can read and change it. Change the DOM and the page updates instantly.

Finding elements

document.querySelector("#title")      // the first match
document.querySelectorAll(".para")    // all of them

Both take a CSS selector ~ exactly the syntax you already know from stylesheets. #id, .class, p, nav a, all of it.

querySelector gives you one element, or null if nothing matched. querySelectorAll gives you a list you can loop over.

Changing them

el.textContent = "new text";
el.style.color = "crimson";
el.classList.add("active");
el.setAttribute("href", "/about/");

Prefer classList over style. Setting .style line by line scatters your design across your JavaScript. Adding a class keeps the look in the stylesheet and the behaviour in the script, which is where they each belong.

textContent vs innerHTML

textContent handles plain text. innerHTML accepts markup ~ which means anything a visitor typed can become real HTML on your page. That’s a genuine security hole. Use textContent unless you have a specific reason not to.

Making new elements

const item = document.createElement("li");
item.textContent = "Hello";
list.append(item);

createElement builds it in memory. Nothing shows up until you append it to something already on the page.

If nothing works

querySelector returning null almost always means your <script> ran before the HTML existed. Move it to the bottom of the <body>.

Next demoEvents
Keyboard Shortcuts
⌘ Z / ⌘ ⇧ ZCtrl Z / Ctrl ⇧ Z Undo / redo
Tab / ⇧ TabTab / ⇧ Tab Indent / unindent selection
⌘ ] / ⌘ [Ctrl ] / Ctrl [ Indent / unindent lines
⌘ ACtrl A Select all
⌘ DCtrl D Select next occurrence of selection
⌘ /Ctrl / Comment / uncomment lines
Ctrl SpaceCtrl Space Autocomplete
Ctrl EnterCtrl Enter Reset layout
⌘ ⌥ [ / ⌘ ⌥ ]Ctrl ⇧ [ / Ctrl ⇧ ] Fold / unfold block
Code
The editor didn't load — try refreshing the page. Navigation, shortcuts and the info panel still work in the meantime.
Preview
Dimensions0 × 0
Delay
Console