Chapter 13 of 16All chapters
Chapter 13 of 16
The DOM
Reading and changing the page.
Finding elements
document.querySelector takes a CSS selector and returns the first match, and querySelectorAll returns all of them as a static list. Both are enough for almost everything.
- textContent sets text safely. innerHTML parses markup, so never feed it untrusted input.
- classList.add, remove and toggle are how you drive CSS state.
Building nodes
document.createElement makes an element, append puts it in place, and remove takes it out. Building a string and assigning innerHTML once is faster than many small insertions.