Track 01 · Lesson 9 of 9How the web works

Track 01 · How the web works

Changing the page with JavaScript

Lesson 9 of 9· 6 min

A handful of DOM methods cover most everyday work: find elements, change their text or classes, and add or remove nodes. Run each line and watch the page react.

Run it, watch it

Click a line to run it

Run a line of JavaScript

The page

Console

// Click a line on the left to run it

The everyday toolkit#

  • Find: document.querySelector(selector) returns the first match, querySelectorAll returns all of them. Both take the same CSS selectors you write in stylesheets.
  • Change: textContent for text, classList.add, remove and toggle for classes, style for one-off inline styles.
  • Create and add: document.createElement("li"), fill it in, then append it where it belongs.
  • Remove: call remove() on the element.

When nothing matches, querySelector returns null, and calling anything on null throws a TypeError. Remove every item in the demo, then try to change one, to see it happen.

textContent versus innerHTML#

Run both "Call mom" lines and compare. textContent shows the tags as plain characters. innerHTML parses them as HTML. That's handy for markup you wrote yourself, and dangerous for anything a user typed: if a comment contains a script, innerHTML will happily build it. That's the root of cross-site scripting, which you'll take apart in Attacks and defenses.

Check yourself

Which is safe for showing a user's comment on the page?