The DOM: find and change page elements

Select elements, change their text and styles, and create new elements from data.

Module 6: JavaScript in the browser · Lesson 19 of 25 · 18 min read · Free

When the browser reads your HTML, it builds a tree of objects called the DOM (Document Object Model). JavaScript can read and change that tree — and the page updates instantly.

The DOM tree

Connecting your script

Put your script just before </body>, so the HTML exists when it runs:

  <script src="app.js"></script>
</body>

Find elements

document.querySelector("#cart-count");      // the first match for a CSS selector
document.querySelector(".card");            // first element with class "card"
document.querySelectorAll(".card");         // ALL matches (a list)
document.getElementById("search");          // by id (no #)

You use the same selectors as CSS.

Change elements

<h1 id="title">Welcome</h1>
<p class="note">Prices may change.</p>
<p>Cart: <span id="count">0</span> items</p>
<script>
  const title = document.querySelector("#title");
  title.textContent = "Mama Nkechi's Provisions";       // change text
  title.style.color = "#08783f";                        // change a style

  document.querySelector(".note").classList.add("hidden");  // add a class...
  document.querySelector("#count").textContent = 3;
</script>
<style>.hidden { display: none; }</style>
  • textContent — the text inside an element.
  • classList.add / remove / toggle("name") — the best way to change appearance: keep styles in CSS and switch classes.
  • style.property — set one style directly (fine for quick changes).
  • setAttribute("href", "..."), element.value (for inputs), element.hidden = true.

Create elements from data

This is how product lists, search results and messages get onto the page:

<div id="products"></div>
<script>
  const products = [
    { id: 1, name: "Mama Gold Rice 5kg", price: 9500 },
    { id: 2, name: "Golden Penny Semovita 2kg", price: 3800 },
    { id: 5, name: "Peak Milk Tin 160g", price: 950 },
  ];
  const box = document.getElementById("products");
  box.innerHTML = "";                       // clear old content
  for (const p of products) {
    const card = document.createElement("article");
    card.className = "card";
    const name = document.createElement("h3");
    name.textContent = p.name;
    const price = document.createElement("p");
    price.textContent = "₦" + p.price.toLocaleString("en-NG");
    const btn = document.createElement("button");
    btn.className = "add-btn";
    btn.dataset.id = p.id;                  // becomes data-id="1"
    btn.textContent = "Add to cart";
    card.append(name, price, btn);
    box.append(card);
  }
</script>
<style>
  #products { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; font-family: system-ui, Arial; }
  .card { border: 1px solid #ddd; border-radius: 10px; padding: 10px; }
</style>

Inspect the result in DevTools after running it in a real page: the cards are real DOM elements, with data-id attributes ready for the next lesson.

Check yourself

Answer in your head first, then open each question to see the answer and why.

  1. Which method returns all elements that match a CSS selector?

    • A document.querySelectorAll(".card")
    • B document.querySelector(".card")
    • C document.getElementById("card")
    • D document.find(".card")
    Show the answer

    A) document.querySelectorAll(".card") — querySelectorAll returns every match; querySelector only the first.

  2. Why use textContent rather than innerHTML for text that came from a user?

    • A innerHTML would run any HTML or script they typed (XSS)
    • B textContent is shorter to type
    • C innerHTML doesn't work
    • D There's no difference
    Show the answer

    A) innerHTML would run any HTML or script they typed (XSS) — textContent always treats input as plain text.

  3. What does btn.dataset.id = 5 create?

    • A A data-id="5" attribute
    • B An id="5" attribute
    • C A class
    • D Nothing
    Show the answer

    A) A data-id="5" attribute — dataset maps to data-* attributes.

More free lessons: What front-end developers do · Set up VS Code, Chrome and Live Server · Text, links and images · Selectors, colours and fonts · Mobile-first design and media queries · Variables, data types and operators · Git and GitHub