Reading history

JavaScript DOM Tutorial: querySelector, textContent, classList

5 min read Updated 1 views

Learn the JavaScript DOM: select elements with querySelector, change text, styles and classes, create and remove elements, and use attributes.

Behind every web page, the browser keeps a live model of it called the DOM (Document Object Model): a family tree of objects, one for each tag, built as the HTML is read. JavaScript can walk this tree to find any element, read it and change it. Rewriting a heading, adding items to a list, switching a CSS class or deleting an element all go through the DOM, and the screen updates at once with no reload.

In this lesson you will learn

  • What the DOM tree is
  • Selecting elements with querySelector and getElementById
  • Changing text, HTML, styles and classes
  • Creating, adding and removing elements
  • Reading and setting attributes and data-* values

The DOM Tree

For a page with a heading and a list, the browser builds a tree like this:

document
└── html
    ├── head
    │   └── title
    └── body
        ├── h3#title
        └── ul#list
            ├── li
            └── li

The global document object is the root. Every element is an object with properties (textContent, id, style) and methods (append(), remove()).

Selecting and Changing Elements

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DOM</title>
  <style>
    body { font-family: sans-serif; }
    .done { text-decoration: line-through; color: #888; }
    .highlight { background: #fff3cd; }
  </style>
</head>
<body>
  <h3 id="title">Shopping list</h3>
  <ul id="list">
    <li>Rice</li>
    <li>Eggs</li>
  </ul>
  <p class="note">Items are added by JavaScript below.</p>
  <script>
    const title = document.querySelector("#title");
    title.textContent = "Shopping list (updated by JS)";
    title.style.color = "#00695c";

    const list = document.querySelector("#list");
    for (const item of ["Milk", "Bread"]) {
      const li = document.createElement("li");
      li.textContent = item;
      list.appendChild(li);
    }

    const items = document.querySelectorAll("#list li");
    items[0].classList.add("done");
    document.querySelector(".note").classList.add("highlight");
    document.querySelector(".note").textContent += " Total items: " + items.length;
  </script>
</body>
</html>

Result

  • document.querySelector("#title") returns the first element matching a CSS selector. It accepts any selector you would use in CSS, such as .note or ul li.
  • document.querySelectorAll("#list li") returns all matches as a list you can loop over with for...of or index like an array.
  • textContent reads or replaces an element’s text. style.color sets an inline style; CSS property names become camelCase, so background-color is style.backgroundColor.
  • document.createElement("li") makes a new element, and appendChild() (or append()) puts it into the page.
  • classList.add(), remove() and toggle() switch CSS classes. Changing classes is usually cleaner than setting many inline styles.

Content, Attributes and Removing

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DOM attributes</title>
  <style>body { font-family: sans-serif; } .box { padding: 8px; border: 2px solid #6a1b9a; }</style>
</head>
<body>
  <div class="box" id="box">Original <b>bold</b> text</div>
  <a id="link" href="#first">A link</a>
  <pre id="log"></pre>
  <script>
    const box = document.getElementById("box");
    const link = document.getElementById("link");
    const log = document.getElementById("log");

    log.textContent += "textContent: " + box.textContent + "\n";
    log.textContent += "innerHTML:   " + box.innerHTML + "\n";

    link.setAttribute("href", "#second");
    log.textContent += "href is now: " + link.getAttribute("href") + "\n";

    box.dataset.status = "checked";
    log.textContent += "data-status: " + box.dataset.status + "\n";

    box.style.background = "#f3e5f5";
    box.remove();
    log.textContent += "box removed; still in page? " + document.body.contains(box);
  </script>
</body>
</html>

Result

  • textContent gives only the text; innerHTML gives the HTML markup inside the element.
  • getAttribute() and setAttribute() read and write any attribute, such as href or src.
  • dataset reads and writes data-* attributes: dataset.status maps to data-status. They are handy for storing small bits of information on elements.
  • element.remove() takes an element out of the page.

DOM Cheat Sheet

TaskCode
Find one elementdocument.querySelector(".card")
Find alldocument.querySelectorAll(".card")
Change textel.textContent = "Hi"
Toggle a classel.classList.toggle("open")
Create and addparent.append(document.createElement("p"))
Removeel.remove()
Read a form valueinput.value

Common Mistakes

  1. Running the script before the HTML exists, so querySelector returns null. Put scripts at the end of the body or use defer.
  2. Forgetting the # or . in querySelector. (getElementById takes the id without #.)
  3. Treating querySelectorAll as one element: list.textContent = "x" does nothing useful; loop over it.
  4. Putting user input into innerHTML, which can run malicious HTML. Use textContent for text.

Practice Exercises

Exercise 1. Change the text of every <p> with class price to “Sold out”.

Show answer
for (const p of document.querySelectorAll("p.price")) {
  p.textContent = "Sold out";
}

Exercise 2. Build a <ul> from the array ["HTML", "CSS", "JS"] and add it to the body.

Show answer
const ul = document.createElement("ul");
for (const topic of ["HTML", "CSS", "JS"]) {
  const li = document.createElement("li");
  li.textContent = topic;
  ul.append(li);
}
document.body.append(ul);

Frequently Asked Questions

Should I use getElementById or querySelector?

Both work. getElementById is slightly faster and only finds by id; querySelector accepts any CSS selector, so many developers use it everywhere for consistency.

Is the DOM part of JavaScript?

No. The DOM is a browser feature that JavaScript can use. That is why document does not exist when you run code in Node.js.

Summary

  • The DOM is the browser’s tree of objects built from HTML.
  • querySelector and querySelectorAll find elements with CSS selectors.
  • Change pages with textContent, classList, style and attributes.
  • createElement, append and remove add and delete elements.

Next: JavaScript Events.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *