Home/Learn/JavaScript & TypeScript/The DOM — Selecting and Changing the Page

The DOM — Selecting and Changing the Page

Beginner
The Browser

The DOM is a tree of objects representing the page. You will mostly let React manage it, but understanding it is what lets you debug React and handle the cases React does not cover.

Overview

When the browser parses HTML it builds a tree of node objects — the Document Object Model — and JavaScript can read and change that tree, with the page updating to match. React exists precisely so you do not do this by hand, which leads people to skip learning it. That is a mistake for two reasons: React problems are DOM problems underneath, and there are real tasks — focus management, measuring an element, integrating a non-React library — where you reach for the DOM directly through a ref.

Selecting Elements

querySelector takes any CSS selector and is the only one you need most of the time.

querySelector, and live vs static lists
document.querySelector('.card')            // first match, or null
document.querySelectorAll('.card')         // static NodeList of all matches
document.getElementById('root')            // fastest, id only

// querySelectorAll returns a static list — not live
const items = document.querySelectorAll('li')   // snapshot
// getElementsByClassName returns a LIVE collection that updates itself,
// which causes infinite loops if you append inside a loop over it

// NodeList has forEach but not map; convert when you need array methods
[...document.querySelectorAll('li')].map(li => li.textContent)

// Searching within an element, not the whole document
card.querySelector('.title')

Reading and Changing

textContent for text, classList for classes, dataset for custom data. innerHTML is the one to be careful with.

textContent, classList, dataset
el.textContent = 'Safe — treated as text'
el.innerHTML = userInput          // XSS if userInput is not trusted

el.classList.add('active')
el.classList.remove('hidden')
el.classList.toggle('open', isOpen)     // second arg forces the state
el.classList.contains('active')

el.dataset.problemId = '42'       // <div data-problem-id="42">
el.dataset.problemId              // '42' — always a string

// Attributes vs properties — they can diverge
input.value = 'typed'             // the current value
input.getAttribute('value')       // the original HTML attribute

// Creating and inserting
const li = document.createElement('li')
li.textContent = title
list.append(li)                   // append takes strings too
li.remove()

Layout Thrashing

Reading a layout property forces the browser to recalculate. Alternating reads and writes in a loop is the classic performance bug.

Read all, then write all
// Bad — forces a synchronous layout on every iteration
items.forEach(el => {
  el.style.height = el.offsetHeight + 10 + 'px'   // read, write, read, write
})

// Better — batch the reads, then the writes
const heights = items.map(el => el.offsetHeight)   // all reads
items.forEach((el, i) => {                          // all writes
  el.style.height = heights[i] + 10 + 'px'
})

// Properties that force layout when read:
// offsetTop/Left/Width/Height, clientWidth/Height,
// scrollTop/Height, getBoundingClientRect(), getComputedStyle()

Key Points to Remember

  • 1querySelector/querySelectorAll accept any CSS selector and cover nearly every selection need
  • 2querySelectorAll returns a static snapshot; getElementsBy* return live collections that update as you mutate
  • 3textContent is safe; innerHTML with untrusted input is an XSS vulnerability
  • 4dataset reads and writes data-* attributes, and values are always strings
  • 5Reading offsetHeight or getBoundingClientRect forces layout — batch reads before writes to avoid thrashing

Interview Questions

Sign in to ask Aria
1

What is the difference between textContent and innerHTML, and when is innerHTML dangerous?

Easy
2

What is the difference between a live HTMLCollection and a static NodeList?

Medium
3

What is layout thrashing and how do you avoid it?

Hard

Ask Aria about The DOM — Selecting and Changing the Page

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…