Coding Hub  /  Reference

the dom

Finding elements, changing them, making new ones, and responding to clicks. Both playgrounds below run on the same little document, so you can see every method work.

selector playground — type a CSS selector, watch what it picks

  

Part one: what the DOM is

Three ideas. Get these and the rest of the page is just method names.

01 The DOM is not your HTML

Your .html file is text. The browser reads it once and builds a live tree of objects in memory. That tree is the Document Object Model, and it is what JavaScript talks to.

Two consequences that explain a lot of confusion:

  • Changing the DOM never changes your file. Reload and your edits are gone.
  • The browser repairs broken markup while building the tree, so what you inspect can differ from what you typed.

"View source" shows the file the server sent. The Elements tab in devtools shows the live DOM. When they disagree, something changed the tree after loading — usually your own script.

text in, tree out
Your file                     The tree the browser builds

<ul id="list">                 ul#list
  <li class="plant">            └── li.plant
    <h3>Fern</h3>                   └── h3
  </li>                                └── "Fern"   (a text node)
</ul>

02 Nodes and the tree

Everything in the tree is a node. Elements are nodes, but so is every piece of text, and so is every comment.

That is why there are two sets of navigation properties. The childNodes set counts text and comments; the children set skips them and gives you elements only.

Whitespace between tags is a text node. list.childNodes.length on a nicely indented list counts the newlines too, which is almost never what you want. Reach for the element versions.

nodes vs elements
Counts everythingElements only
childNodeschildren
firstChildfirstElementChild
lastChildlastElementChild
nextSiblingnextElementSibling
previousSiblingpreviousElementSibling
parentNodeparentElement

03 When your script runs

The single most common beginner bug: a <script> in the <head> runs before the body exists, so every querySelector returns null.

Three fixes. The first is the modern answer, the second is the old reliable one, and the third is what you use when you cannot move the tag.

defer also keeps your scripts in order and lets the HTML carry on parsing. Prefer it to async for anything that touches the page.

three ways
<!-- 1. Best: defer, in the head -->
<script src="app.js" defer></script>

<!-- 2. Also fine: last thing before </body> -->
<script src="app.js"></script>

<!-- 3. When the tag cannot move: wait for the event -->
app.js
document.addEventListener('DOMContentLoaded', () => {
  // The tree is built. Safe to query now.
  const list = document.querySelector('#list')
})

// DOMContentLoaded fires when the HTML is parsed.
// 'load' waits for images and stylesheets too — usually later than you need.

Part two: finding things

Try every selector in this part in the playground at the top of the page.

04 querySelector

Two methods, any CSS selector you can write in a stylesheet. These are the ones to use.

querySelector returns the first match or null. querySelectorAll returns a NodeList of every match, which is empty rather than null when nothing matches.

Forgetting the . or # is the classic slip: querySelector('plant') looks for a <plant> tag and quietly gives you null.

You can call them on an element, not just document, and the search is then limited to inside it: card.querySelector('.name').

the two
document.querySelector('.plant')        // first match, or null
document.querySelectorAll('.plant')     // all matches, maybe empty

// Any CSS selector works
document.querySelector('#list > li:first-child')
document.querySelectorAll('[data-id="2"]')
document.querySelectorAll('button:disabled')
document.querySelectorAll('.plant:not(.thirsty)')

// Scoped to one element
const card = document.querySelector('.plant')
card.querySelector('.name')             // only inside that card

05 The getElementBy family

Older methods you will meet in existing code and tutorials. They still work; you rarely need them now.

The big difference is that getElementsByClassName and getElementsByTagName return live collections that update themselves as the page changes. Removing items inside a for loop over a live collection skips half of them, because the collection shrinks while you count up through it.

old and new
OlderReturnsModern equivalent
getElementById('list')element or nullquerySelector('#list')
getElementsByClassName('plant')live collectionquerySelectorAll('.plant')
getElementsByTagName('li')live collectionquerySelectorAll('li')
getElementsByName('email')live collectionquerySelectorAll('[name="email"]')
no # or . on getElementById
document.getElementById('list')     // no '#' — just the id
document.querySelector('#list')     // '#' required here

06 NodeList is not an array

A NodeList looks like an array — it has a length and you can index it — but it is missing most array methods.

forEach happens to work on a NodeList. map, filter and reduce do not. Spread it into a real array when you need those.

converting
const items = document.querySelectorAll('.plant')

items.length                      // works
items[0]                          // works
items.forEach(el => ...)          // works
items.map(el => el.textContent)   // TypeError: items.map is not a function

const real = [...items]           // now a real array
real.map(el => el.textContent)    // works
Array.from(items)                 // the same thing, older spelling

// Count matches without converting
document.querySelectorAll('.thirsty').length

07 Moving around the tree

Once you have one element you can walk to its relatives without another query.

closest is the one worth memorising: it walks upward looking for the nearest ancestor that matches, including the element itself. It is how a click on a button finds the card it belongs to.

navigation
const name = document.querySelector('.name')

name.parentElement                 // the li
name.closest('li')                 // nearest matching ancestor — the li
name.closest('.plant')             // same li here
name.nextElementSibling            // the .tag beside it

const list = document.querySelector('#list')
list.children                      // the three li elements
list.firstElementChild             // the first li
list.children.length               // 3

// The pattern you will use constantly
button.closest('li').remove()      // delete the whole card the button sits in

Part three: reading and changing

You have an element. Now change what it says, what it looks like, and what it carries.

08 textContent vs innerHTML

Three properties that look interchangeable and are not.

Use textContent for text. innerHTML parses whatever you give it as markup, so text that came from a user can inject tags and scripts into your page. That is the XSS bug, and it is the most common security hole in beginner front-end code.

innerText is aware of CSS: it skips hidden elements and collapses whitespace the way the screen shows it. It also forces the browser to recalculate layout, so it is slower in a loop.

the three
PropertyGives youUse for
textContentall text, including hiddendefault reading and writing text
innerTexttext as rendered on screenwhen hidden elements must be skipped
innerHTMLthe markup insidemarkup you wrote, never user text
outerHTMLthe element and its markupinspecting, replacing the element itself
why it matters
const name = document.querySelector('.name')

name.textContent = 'Fern'               // safe, always
name.innerHTML = '<em>Fern</em>'        // fine — markup you wrote

// Now imagine `typed` came from an input box
const typed = '<img src=x onerror="steal()">'
name.innerHTML = typed                  // the script runs. XSS.
name.textContent = typed                // shows the characters. Safe.

09 Attributes vs properties

An attribute is what you wrote in the HTML. A property is what lives on the live object. They start out matching and then drift apart.

Type into a text box and its value property changes, but the value attribute still holds whatever the HTML said. For form state — value, checked, disabled — always read the property.

which to use
const input = document.querySelector('input')

input.value                      // what is in the box RIGHT NOW  <- use this
input.getAttribute('value')      // what the HTML said at load

input.checked = true             // property: a real boolean
input.disabled = false

// Attributes are for things with no property, and for custom ones
el.getAttribute('href')
el.setAttribute('aria-expanded', 'true')
el.removeAttribute('disabled')
el.hasAttribute('data-id')       // true / false

10 classList

Never build a class string by hand. classList has a method for every case and cannot clobber the classes you did not mean to touch.

el.className = 'active' replaces every class on the element. One careless assignment and the styling that was already there is gone.

Changing a class is almost always better than changing style directly: the look stays in your stylesheet, where you can see it all at once.

classList
el.classList.add('thirsty')
el.classList.remove('thirsty')
el.classList.toggle('thirsty')          // on if off, off if on
el.classList.toggle('thirsty', isDry)   // force it on or off
el.classList.contains('thirsty')        // true / false
el.classList.replace('thirsty', 'healthy')

el.classList.add('a', 'b', 'c')         // several at once

// Everything at once, the dangerous way
el.className = 'thirsty'                // wipes all other classes

11 style and CSS variables

el.style reaches only the inline style attribute. Reading it gives you nothing for rules that came from your stylesheet, which surprises people.

Property names become camelCase: background-color is backgroundColor. Values are strings, and lengths need their units or nothing happens.

style
el.style.color = 'red'
el.style.backgroundColor = '#eee'       // camelCase, not background-color
el.style.width = '200px'                // units required
el.style.width = 200                    // silently does nothing

el.style.display = 'none'               // hide
el.style.display = ''                   // back to whatever the CSS says

// Reading the computed value — what is ACTUALLY applied
getComputedStyle(el).color              // 'rgb(255, 0, 0)'

// CSS custom properties need the long form
el.style.setProperty('--accent', '#2049A8')
getComputedStyle(el).getPropertyValue('--accent')

12 dataset

Any attribute beginning data- is yours to invent, and all of them show up on el.dataset.

This is how an element remembers which record it represents — the database id on a card, so a click handler knows what to delete.

Dataset values are always strings. el.dataset.id on data-id="2" gives '2', so comparing with === 2 is false. Convert with Number().

The name converts: data-plant-id becomes dataset.plantId.

dataset
// <li data-id="2" data-plant-name="Monstera">

el.dataset.id                 // '2'      a string, always
el.dataset.plantName          // 'Monstera'   data-plant-name
Number(el.dataset.id)         // 2        now a number

el.dataset.id = 7             // sets data-id="7"
delete el.dataset.id          // removes the attribute

// The pattern it exists for
const id = Number(button.closest('li').dataset.id)
await fetch(`/api/v1/plants/${id}`, { method: 'DELETE' })

Part four: making and removing

The scratchpad below runs real code against the same sample document and shows you the markup that comes out.

13 Creating elements

Three steps, always in this order: make it, fill it, put it somewhere. An element you create exists in memory but appears nowhere until you insert it.

Run any of these in the scratchpad and watch the markup underneath change.

dom scratchpad — document here is scoped to the sample below

  

14 Inserting

append and prepend cover almost everything. They take several things at once and accept plain strings, which become text nodes safely.

The old appendChild still works but takes exactly one node and no strings. There is no reason to reach for it in new code.

where things go
parent.append(el)           // inside, at the end
parent.prepend(el)          // inside, at the start
el.before(other)            // outside, just before el
el.after(other)             // outside, just after el

parent.append(a, b, 'text') // several at once; strings are safe text

// Precise placement with one call
el.insertAdjacentElement('beforebegin', other)
el.insertAdjacentHTML('beforeend', '<span>hi</span>')

//   beforebegin  <div>  afterbegin ... beforeend  </div>  afterend

15 Removing and cloning

remove() takes the element out of the tree. The object still exists in memory as long as a variable points at it, so you can put it back.

cloneNode(false) copies only the element. cloneNode(true) copies everything inside it, which is nearly always what you want. Neither copies event listeners.

removing, replacing, copying
el.remove()                     // take it out

parent.replaceChildren()        // empty the parent, cleanly
parent.innerHTML = ''           // same effect, older habit

el.replaceWith(other)           // swap one element for another

const copy = el.cloneNode(true) // deep copy, contents included
const shell = el.cloneNode(false) // the element only, empty
// Listeners are never copied — attach them again

16 Building many rows

Appending inside a loop touches the live page on every pass, and the browser may recalculate layout each time. For a handful of rows it does not matter; for hundreds it does.

A DocumentFragment is a lightweight holding box that is not part of the page. Fill it, then insert it once. Appending a fragment moves its children in and leaves the fragment empty.

one insert instead of many
const list = document.querySelector('#list')
const frag = document.createDocumentFragment()

for (const plant of plants) {
  const li = document.createElement('li')
  li.className = 'plant card'
  li.dataset.id = plant.id
  li.textContent = plant.nickname    // safe: text, not markup
  frag.append(li)                    // off-page, cheap
}

list.append(frag)                    // one touch of the live page

Part five: events

Making the page respond. One method, and two patterns worth knowing well.

17 addEventListener

Element, event name, function. The name has no on prefix: 'click', not 'onclick'.

Pass the function, do not call it. addEventListener('click', handleClick) is right; handleClick() runs it immediately and registers whatever it returned.

To remove a listener later you need the same function reference, so an inline arrow function can never be removed. Name it, or use { once: true }.

listening
button.addEventListener('click', handleClick)      // right
button.addEventListener('click', handleClick())    // wrong — calls it now

button.addEventListener('click', (event) => {
  console.log('clicked', event.target)
})

button.addEventListener('click', run, { once: true })   // fires once
button.removeEventListener('click', run)                // same reference needed
events worth knowing
EventFires when
clickclicked, or activated by keyboard on a real button
inputthe value changes, on every keystroke
changethe value changed and the field lost focus
submita form is submitted — listen on the <form>
keydowna key goes down; event.key is 'Enter', 'Escape'…
DOMContentLoadedthe HTML is parsed and the tree is ready

18 The event object

Your handler receives an object describing what happened.

target is what was actually clicked, which may be a child. currentTarget is the element the listener is attached to. Click the text inside a button and target can be that text's element, not the button — this is the source of a great many "why didn't it work" moments.

the useful properties
function handle(event){
  event.target           // the deepest element that was clicked
  event.currentTarget    // the element this listener is on
  event.type             // 'click'
  event.key              // on keyboard events: 'Enter', 'Escape', 'a'

  event.preventDefault()   // stop the browser's default action
  event.stopPropagation()  // stop it travelling up to ancestors
}

// The one you will use most: stop a form reloading the page
form.addEventListener('submit', (event) => {
  event.preventDefault()
  // ...now send it with fetch instead
})

19 Event delegation

Events travel upward from the element that was hit, through every ancestor. That is called bubbling, and you can use it.

Instead of a listener on every button, put one on the container and work out what was clicked. This is faster, and — the real reason — it keeps working for elements you add later, which a per-button listener never does.

closest is the other half of the pattern: it turns "whatever got clicked" into "the button, if the click was anywhere inside one".

one listener for a whole list
const list = document.querySelector('#list')

list.addEventListener('click', (event) => {
  // Was the click inside a .water button?
  const button = event.target.closest('.water')
  if (!button) return               // clicked elsewhere; ignore

  const card = button.closest('li')
  const id = Number(card.dataset.id)

  card.classList.remove('thirsty')
  console.log('watering plant', id)
})

// New cards appended later are handled too, with no extra wiring.

20 Forms and inputs

Listen for submit on the form, not click on the button. Submit also fires when someone presses Enter in a field, which a click listener misses.

An input's value is always a string, even on type="number". Convert before arithmetic or you get '5' + 1 === '51'.

a form handler
const form = document.querySelector('#add-plant')

form.addEventListener('submit', async (event) => {
  event.preventDefault()              // or the page reloads

  const nickname = form.nickname.value.trim()   // by name attribute
  const days = Number(form.days.value)          // string -> number

  if (!nickname) return

  // Everything at once, for a form with many fields
  const data = Object.fromEntries(new FormData(form))

  await fetch('/api/v1/plants', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ nickname, wateringIntervalDays: days })
  })

  form.reset()
})

Part six: when it breaks

Four messages account for most DOM bugs in a first year.

21 Errors you will meet

Read the message. Each of these names its own cause once you know the vocabulary.

message → cause
What you seeWhat it means
Cannot read properties of null (reading 'textContent')Your querySelector found nothing. Either the script ran before the HTML, or the selector is wrong — check for a missing . or #.
Cannot set properties of nullSame cause, on an assignment.
items.map is not a functionquerySelectorAll gives a NodeList. Spread it first: [...items].
Failed to execute 'querySelector': not a valid selectorA typo in the selector string — often a stray quote or a missing bracket.
The handler runs once, then never againSomething replaced the elements with innerHTML, which throws away their listeners. Delegate instead.
Clicking does nothing at allThe listener was attached before the element existed, or you wrote handleClick() instead of handleClick.
The page reloads when you submitMissing event.preventDefault() in the submit handler.
A number is being joined instead of addedinput.value is a string. Wrap it in Number().
Your styling disappearedel.className = '...' replaced every class. Use classList.add.
Width or position is ignoredA length was set without units: el.style.width = 200 does nothing.

22 Quick reference

Everything on this page, in the order you normally need it.

the whole page in one block
// FIND
document.querySelector('.card')          // first, or null
document.querySelectorAll('.card')       // NodeList
el.closest('li')                         // nearest matching ancestor
el.children                              // element children
[...nodeList]                            // make it a real array

// READ AND WRITE
el.textContent = 'safe text'             // default choice
el.innerHTML = '<em>your markup</em>'    // never user input
el.value                                 // form fields, live
el.dataset.id                            // data-id, always a string
el.getAttribute('href')

// CLASSES AND STYLE
el.classList.add('on')
el.classList.toggle('on', condition)
el.classList.contains('on')
el.style.backgroundColor = '#eee'        // camelCase, units required
getComputedStyle(el).color               // what is actually applied

// MAKE AND MOVE
const el = document.createElement('li')
parent.append(el)                        // or prepend, before, after
el.remove()
el.cloneNode(true)                       // deep copy, no listeners
document.createDocumentFragment()        // batch many inserts

// EVENTS
el.addEventListener('click', handler)    // no 'on', pass don't call
event.target                             // what was hit
event.currentTarget                      // what is listening
event.preventDefault()                   // stop the default action
list.addEventListener('click', (e) => {  // delegation
  const btn = e.target.closest('.water')
  if (!btn) return
})