Lesson 4 of 6 · 5 min

The DOM

Find elements with querySelector, change their text, attributes and classes, create and remove elements, and render a list from data safely.

On this page
  1. Finding elements
  2. Changing text
  3. Attributes and properties
  4. Classes and styles
  5. Creating and removing elements
  6. Rendering a list from data
  7. Moving around the tree
  8. Try it

When the browser loads HTML, it builds a tree of objects called the DOM (Document Object Model). JavaScript changes the page by changing that tree, and the browser redraws the result.

Finding elements

const title = document.querySelector("h1")                 // the first match
const button = document.querySelector("#theme-toggle")     // by id
const cards = document.querySelectorAll(".card")            // every match
const firstLink = document.querySelector("nav a")

querySelector uses the same selectors as CSS. It returns null when nothing matches, so check before using the result if the element might not exist.

querySelectorAll returns a list you can loop over:

for (const card of cards) {
  console.log(card.textContent)
}

Changing text

title.textContent = "Welcome back"

textContent treats the value as plain text, which is safe for anything a user typed. innerHTML parses the value as HTML. Never put user input or API data into innerHTML without escaping it, or someone can inject a script into your page (cross-site scripting, XSS).

Attributes and properties

const link = document.querySelector("a")
link.href = "/courses"
link.setAttribute("aria-current", "page")
link.getAttribute("href")
link.removeAttribute("target")

const input = document.querySelector("#email")
input.value          // what's typed in the box
input.disabled = true

Custom data goes in data- attributes and is read through dataset:

<button data-lesson-id="42">Mark as done</button>
button.dataset.lessonId  // "42"

Classes and styles

Change the look by toggling classes, and keep the actual styles in CSS:

card.classList.add("is-active")
card.classList.remove("is-active")
card.classList.toggle("is-open")
card.classList.contains("is-open")  // true or false

You can set inline styles, but it's best kept for values calculated in JavaScript:

bar.style.transform = `scaleX(${progress})`
document.documentElement.style.setProperty("--accent", "#0a0a0a")

Creating and removing elements

const item = document.createElement("li")
item.textContent = "New lesson"
item.className = "lesson"

const list = document.querySelector("#lessons")
list.append(item)        // add at the end
list.prepend(item)       // or at the start
item.remove()            // take it out again

Rendering a list from data

A common pattern: data in an array, turned into elements.

const lessons = [
  { title: "How CSS works", minutes: 6 },
  { title: "Selectors", minutes: 8 },
]

const list = document.querySelector("#lessons")
list.replaceChildren(
  ...lessons.map((lesson) => {
    const li = document.createElement("li")
    li.textContent = `${lesson.title} (${lesson.minutes} min)`
    return li
  })
)

replaceChildren clears the list and adds the new items in one step, and textContent keeps it safe from injected HTML.

Moving around the tree

item.parentElement
item.closest(".card")       // the nearest ancestor matching a selector
list.children               // direct child elements
item.nextElementSibling

Try it

On a page with an empty <ul id="topics">, write JavaScript that renders ["HTML", "CSS", "JavaScript", "SQL"] as list items. Then add the class is-active to the third item and style it in CSS.

More from JavaScript Crash Course