Nishaglobal Education logo

The DOM: finding and changing page elements

Use the DOM to find elements with querySelector and querySelectorAll, change their text, classes and attributes, and create, add and remove elements with JavaScript.

Lesson 8 of 1340 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Select elements with querySelector and querySelectorAll
  • Change text, classes and attributes safely
  • Create, add and remove elements
Outline
  1. What you'll learn and why it matters
  2. Finding elements
  3. Changing text and HTML
  4. Changing classes and styles
  5. Working with many elements
  6. Creating and removing elements
  7. Practice
  8. Common mistakes
  9. Recap
  10. Quiz
  11. Mark lesson complete

What you'll learn and why it matters

Until now your JavaScript has talked only to the console. The real power comes from changing the page: showing a message, updating a basket count, adding a new item to a list. The browser turns your HTML into a tree of objects called the DOM (Document Object Model), and JavaScript can read and change every part of it.

Finding elements

document.querySelector() takes a CSS selector, the same kind you wrote in the HTML & CSS course, and returns the first matching element.

document.querySelector("#price")the browser searches the DOMbodyh1p id="price"✓ matchprice.textContent = "₹45"The page now shows ₹45
JavaScript calls document.querySelector with the selector #price. The browser searches the DOM tree, finds the matching p element and returns it. Changing its textContent updates what the page shows.
JavaScript
const heading = document.querySelector("h1");
const price = document.querySelector("#price");
const firstItem = document.querySelector(".item");

console.log(heading.textContent);
console.log(price.textContent);
console.log(firstItem.textContent);

price.textContent = "Price: ₹45";

Console (Chrome and Edge)

Masala chai
Price: ₹40
Hot
Show the HTML this script works with
<h1>Masala chai</h1>
<p id="price">Price: ₹40</p>
<ul>
  <li class="item">Hot</li>
  <li class="item">Fresh</li>
</ul>

Live preview: try it

Console

Nothing logged yet.

SelectorFinds
document.querySelector("h1")The first <h1>
document.querySelector("#price")The element with id="price"
document.querySelector(".item")The first element with class="item"
document.querySelectorAll(".item")All elements with that class, as a list

Changing text and HTML

textContent reads or replaces the text inside an element. There is also innerHTML, which reads or replaces the HTML inside it.

Changing classes and styles

The cleanest way to change how something looks is to add or remove a CSS class. The style rules stay in your CSS; JavaScript only switches them on and off.

JavaScript
const card = document.querySelector("#samosa");

card.classList.add("highlight");
console.log(card.classList.contains("highlight"));

card.classList.toggle("sold-out");
console.log(card.className);

Console (Chrome and Edge)

true
card highlight sold-out
Show the HTML and CSS this script works with

HTML

<div class="card" id="samosa">Samosa, ₹25</div>

CSS

.card { padding: 1rem; border: 2px solid #94a3b8; border-radius: 0.75rem; font-family: Arial, sans-serif; }
.highlight { background-color: #fef9c3; border-color: #ca8a04; }
.sold-out { opacity: 0.5; text-decoration: line-through; }

Live preview: try it

Console

Nothing logged yet.

CodeDoes
el.classList.add("x")Adds class x
el.classList.remove("x")Removes class x
el.classList.toggle("x")Adds it if missing, removes it if present
el.classList.contains("x")true if the element has class x
el.style.color = "red"Sets one inline style. Fine for one-off values; prefer classes
el.setAttribute("src", "images/cafe.svg")Sets any attribute, such as src, href or alt

Working with many elements

querySelectorAll returns a list you can loop over with for...of:

JavaScript
const prices = document.querySelectorAll(".price");
let total = 0;

for (const price of prices) {
  total += Number(price.dataset.amount);
  price.classList.add("highlight");
}

console.log(`${prices.length} prices, total ₹${total}`);
document.querySelector("#total").textContent = `Total: ₹${total}`;

Console (Chrome and Edge)

3 prices, total ₹125
Show the HTML and CSS this script works with

HTML

<ul>
  <li class="price" data-amount="40">Masala chai</li>
  <li class="price" data-amount="60">Banana bread</li>
  <li class="price" data-amount="25">Samosa</li>
</ul>
<p id="total"></p>

CSS

.highlight { color: #166534; font-weight: 700; }

Live preview: try it

Console

Nothing logged yet.

data-amount="40" is a data attribute: a place to store your own information on an element. JavaScript reads it with element.dataset.amount. Like everything read from the page, it is a string, so we convert it with Number().

Creating and removing elements

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

JavaScript
const list = document.querySelector("#specials");
const specials = ["Ginger lemon tea", "Veg puff", "Carrot cake"];

for (const special of specials) {
  const li = document.createElement("li");
  li.textContent = special;
  list.append(li);
}

document.querySelector("#loading").remove();
console.log(list.children.length);

Console (Chrome and Edge)

3
Show the HTML this script works with
<h2>Today's specials</h2>
<p id="loading">Loading…</p>
<ul id="specials"></ul>

Live preview: try it

Console

Nothing logged yet.

CodeDoes
document.createElement("li")Makes a new element (not on the page yet)
parent.append(child)Adds it as the last child of parent
parent.prepend(child)Adds it as the first child
el.remove()Removes the element from the page

Practice

Guided exercise

Mark the sold-out items

The menu items have a data-stock attribute. Add the class sold-out to every item whose stock is 0, and show how many are still available in #available.

  1. Select all .menu-item elements with querySelectorAll.
  2. Loop over them; read Number(item.dataset.stock).
  3. If it is 0, add the class; otherwise add 1 to a counter.
  4. Set #available's textContent after the loop.
Show the solution
Solution
const items = document.querySelectorAll(".menu-item");
let available = 0;

for (const item of items) {
  if (Number(item.dataset.stock) === 0) {
    item.classList.add("sold-out");
  } else {
    available++;
  }
}

document.querySelector("#available").textContent = `${available} items available`;
Show the HTML and CSS this script works with

HTML

<ul>
  <li class="menu-item" data-stock="12">Masala chai</li>
  <li class="menu-item" data-stock="0">Banana bread</li>
  <li class="menu-item" data-stock="4">Samosa</li>
</ul>
<p id="available"></p>

CSS

.sold-out { opacity: 0.5; text-decoration: line-through; }

Live preview: try it

Console

Nothing logged yet.

How to get there: Data attributes are strings, so Number() converts them before comparing with === 0. The class does the styling; JavaScript only decides which items get it.

Your turn

Build a list from an array

Given const team = ["Asha", "Ravi", "Meera"];, add each name as an <li> to the empty <ul id="team">, and set the heading #count to 3 members.

Show the solution
Solution
const team = ["Asha", "Ravi", "Meera"];
const list = document.querySelector("#team");

for (const name of team) {
  const li = document.createElement("li");
  li.textContent = name;
  list.append(li);
}

document.querySelector("#count").textContent = `${team.length} members`;
Show the HTML this script works with
<h2 id="count">Team</h2>
<ul id="team"></ul>

Live preview: try it

Console

Nothing logged yet.

How to get there: Create, fill, append: the same three steps for every item. Using textContent keeps it safe even if the names came from a form.

Common mistakes

Running the script before the HTML exists

You see: TypeError: Cannot read properties of null (reading 'textContent')

Fix: Use defer on the script tag, and check the selector matches an element.

Forgetting the # or . in a selector

You see: querySelector("price") looks for a <price> element and returns null

Fix: Ids need #, classes need ..

Treating querySelectorAll like one element

You see: list.textContent = … does nothing useful

Fix: Loop over the list, or use querySelector for one element.

Putting user input into innerHTML

You see: A security hole (XSS) and broken pages

Fix: Use textContent for text.

Recap

  • The DOM is the browser's tree of page objects; JavaScript can read and change it.
  • querySelector finds the first match for a CSS selector; querySelectorAll finds all.
  • Change text with textContent (safe), looks with classList, attributes with setAttribute or dataset.
  • createElement, append and remove add and take away elements.

Key terms

DOM
Document Object Model: the browser's object version of the page that scripts can change.
Data attribute
A custom attribute starting with data-, read in JavaScript with element.dataset.
XSS
Cross-site scripting: an attack where untrusted text is run as code in a page.

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. Which line finds the element with id="total"?

  2. 2. Why use textContent rather than innerHTML for text a visitor typed?

  3. 3. What does `el.classList.toggle("open")` do?

  4. 4. Which three steps add a new list item to a page?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.