Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 122 ยท CSS and JavaScript in HTML

The Document Object Model

Learn how the browser turns HTML into the DOM tree, find elements with querySelector, change text safely, create elements and work with attributes and classList.

When a browser loads your HTML, it does not keep it as text. It builds a live, in-memory model of the page called the Document Object Model, or DOM. Every element, every piece of text and every attribute becomes an object that JavaScript can read and change.

The DOM is the bridge between HTML and JavaScript. Change the DOM and the page on screen updates immediately. In this lesson you will learn how the DOM tree is organized, how to find elements, how to change their text and attributes safely, and how to create new elements from scratch.

HTML becomes a tree

Take this small document:

HTML
<!doctype html>
<html lang="en">
  <head>
    <title>Tide Times</title>
  </head>
  <body>
    <h1>Tide Times</h1>
    <p>High tide at <strong>6:42</strong>.</p>
  </body>
</html>

The browser turns it into a tree of nodes:

TEXT
document
โ””โ”€โ”€ html
    โ”œโ”€โ”€ head
    โ”‚   โ””โ”€โ”€ title
    โ”‚       โ””โ”€โ”€ "Tide Times"
    โ””โ”€โ”€ body
        โ”œโ”€โ”€ h1
        โ”‚   โ””โ”€โ”€ "Tide Times"
        โ””โ”€โ”€ p
            โ”œโ”€โ”€ "High tide at "
            โ”œโ”€โ”€ strong
            โ”‚   โ””โ”€โ”€ "6:42"
            โ””โ”€โ”€ "."

A few words you will see all the time:

  • Node โ€” anything in the tree. The most important kinds are element nodes (<p>) and text nodes (the words inside).
  • Parent, child, sibling โ€” <body> is the parent of <h1> and <p>; they are its children and each other's siblings.
  • document โ€” the root object, and your starting point for everything.

The DOM is not identical to your source code. The browser repairs mistakes, adds missing elements such as <tbody>, and scripts can change it at any time. The Elements panel in DevTools shows the live DOM, while View source shows the original HTML (see Viewing Source and Using DevTools).

Finding elements

Before you can change an element, you need a reference to it. Two methods cover nearly every case, and both take a CSS selector:

  • document.querySelector(selector) โ€” returns the first matching element, or null if there is none.
  • document.querySelectorAll(selector) โ€” returns all matches as a list (a NodeList) that you can loop over.
JavaScript
document.querySelector("h1");              // first <h1>
document.querySelector("#total");          // the element with id="total"
document.querySelector(".card .price");    // first .price inside a .card
document.querySelectorAll("li");           // every <li>
document.querySelectorAll("input[type=checkbox]:checked");

You will also meet document.getElementById("total"), a fast, older method that only finds by id. It needs no #.

Both methods also exist on every element, so you can search inside one part of the page: list.querySelectorAll("li").

Finding and changing elements

Scripts need the elements to exist. These examples put the script after the HTML. In a real page, load your script with defer or as a module so it runs after the document is parsed. See Adding JavaScript.

Changing text: textContent vs innerHTML

There are two common ways to change what is inside an element, and the difference really matters.

  • textContent โ€” gets or sets the element's plain text. Anything you assign is shown literally, even if it looks like HTML.
  • innerHTML โ€” gets or sets the element's content as HTML. Assigned strings are parsed, so tags become real elements.
textContent vs innerHTML

The first paragraph shows the tags as text; the second turns <em> into real italic text.

Never put untrusted text into innerHTML. If a value comes from a user, a URL or another website, someone can smuggle in HTML that runs their own script on your page โ€” an attack called cross-site scripting (XSS). A user name like <img src=x onerror="stealCookies()"> would execute the moment you insert it with innerHTML.

Use textContent for any text, and build elements with createElement() (below). Reserve innerHTML for HTML you wrote yourself.

Creating and adding elements

To add something new to the page, create an element, fill it in, then attach it to the tree:

  1. document.createElement("li") โ€” creates a new, detached element.
  2. Set its textContent, attributes and classes.
  3. Insert it with a method such as append(), prepend(), before() or after().

To remove an element, call its remove() method.

A tiny to-do list

Try adding a task called <b>bold?</b>. It appears as plain text, because textContent never interprets HTML. The submit listener and preventDefault() come from the event lesson.

Working with attributes

Every HTML attribute can be read and changed through the DOM:

  • element.getAttribute("href") โ€” reads an attribute (or null).
  • element.setAttribute("href", "/contact") โ€” sets or adds one.
  • element.removeAttribute("disabled") โ€” removes one.
  • element.hasAttribute("hidden") โ€” checks if it exists.
  • element.toggleAttribute("hidden") โ€” adds it if missing, removes it if present.

Many common attributes are also available as properties with the same name: link.href, image.alt, input.value, button.disabled. Boolean attributes become true/false properties, which is often the most convenient way to work with them.

There is one important difference with form fields: the value attribute is only the field's starting value, while the value property is what is currently typed in it. Read input.value to get what the user entered.

Custom data-* attributes have their own shortcut, element.dataset; you will learn it in Custom Data Attributes.

Two more ways in are worth knowing. element.attributes is a live collection (a NamedNodeMap) of all the element's attributes, each an Attr object with name and value, and you can drop one with element.attributes.removeNamedItem("title"), though removeAttribute() is shorter. An Attr also has isId, which is true only for the id attribute (older browsers; now always read element.id). And document.defaultView returns the window object that displays the document, which is handy in code that receives a document from another frame and needs its window (doc.defaultView.getComputedStyle(el)).

The attributes collection

Changing classes with classList

To change how an element looks, the cleanest approach is to toggle a class and let your CSS do the styling. classList makes that easy:

  • classList.add("active") and classList.remove("active")
  • classList.toggle("active") โ€” add or remove, depending on whether it is there
  • classList.contains("active") โ€” true or false
  • classList.replace("old", "new")
Attributes and classList

Notice the two console lines: getAttribute("href") returns exactly what is in the HTML, while the href property gives the fully resolved URL. classList.toggle() also returns whether the class is now present, which we use to update the button's aria-pressed state for screen readers.

You can set styles directly with element.style.color = "red", as in the first example, but toggling classes keeps all your design decisions in the stylesheet.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does document.querySelector(".price") return if no element has that class?

    querySelector() returns the first match or null. querySelectorAll() would return an empty list.
  2. 2. A comment typed by a visitor needs to be shown on the page. Which is the safe choice?

    textContent shows the text literally, so any HTML or script in the comment is harmless. innerHTML would parse it and open the door to XSS.
  3. 3. Which steps add a new paragraph to the end of an element called box?

    Create the element with document.createElement(), fill it in, then insert it with append().
  4. 4. What does card.classList.toggle("open") do?

    toggle() flips the class and returns true if it is now present.

Summary

  • The browser turns HTML into the DOM, a live tree of nodes that JavaScript can read and change.
  • querySelector() finds the first match for a CSS selector; querySelectorAll() finds them all.
  • textContent sets plain text safely; innerHTML parses HTML and must never receive untrusted input.
  • Build new content with createElement() and insert it with append() and friends; remove it with remove().
  • Use getAttribute()/setAttribute() or properties for attributes, and classList to toggle classes.

You can now structure, style and script a page. Next lesson: Forms โ€” collecting input from your visitors.