Skip to content

Intermediate · JavaScript in the browser: DOM and events · topic 35 of 64 · 30 min

The DOM and changing the page

Explanation

When the browser reads your HTML, it builds a tree of objects called the DOM. JavaScript can find any element in that tree with querySelector, then change its text, classes and attributes, or create new elements. For anything a user typed, use textContent, not innerHTML.

What is the DOM?

When the browser reads your HTML, it builds a model of the page in memory. This model is called the DOM (Document Object Model). Every tag becomes an object, and JavaScript can read and change these objects. When you change the DOM, the browser updates the screen for you.

The DOM is shaped like a tree. The <html> element is the root (the top). Inside it are <head> and <body>, and inside those are more elements. An element inside another one is its child. The outer element is its parent.

Think of it like this: Think of a family tree drawn on paper. The grandparent at the top is <html>, the children are <head> and <body>, and the grandchildren are headings, lists and buttons. JavaScript is a person with a pencil who can find any name on the tree, change it, or add a new child to a branch.
html
<body>
  <h1 id="shop-name">Sharma Kirana</h1>
  <ul id="product-list">
    <li>Rice</li>
    <li>Sugar</li>
  </ul>
</body>
body is the parent of h1 and ul; the ul is the parent of two li elements

Load your script after the HTML

JavaScript can only find elements that already exist. Put your script tag in the head with the defer attribute. defer means: download the file now, but run it only after the whole HTML has been read.

html
<head>
  <meta charset="utf-8">
  <title>Sharma Kirana</title>
  <script src="js/app.js" defer></script>
</head>
With defer, app.js runs when every element of the page is ready

Finding elements

MethodWhat it gives youExample
document.querySelector(css)The first matching element, or nulldocument.querySelector('#shop-name')
document.querySelectorAll(css)A list (NodeList) of all matches; loop with for...ofdocument.querySelectorAll('.product')
document.getElementById(id)The element with that id, or nulldocument.getElementById('cart')
element.closest(css)The nearest parent (or itself) that matchesbutton.closest('li')

Changing what you found

javascript
const title = document.querySelector('#shop-name');
title.textContent = 'Sharma Kirana Store'; // change the text
title.classList.add('highlight');          // add a CSS class
title.classList.remove('old');             // remove a class
title.classList.toggle('open');            // add if missing, remove if there

const link = document.querySelector('a.offer');
link.setAttribute('href', '/offers');      // change an attribute

const card = document.querySelector('.product');
console.log(card.dataset.price);           // reads data-price="40" as '40'

document.querySelector('#loading').hidden = true; // hide an element
The most used ways to change an element

dataset gives you the data- attributes of an element. data-price="40" becomes element.dataset.price, and the value is always a string. A name with a hyphen, like data-product-id, becomes dataset.productId.

Creating elements and drawing a list from data

Real pages often build parts from data: a list of products, exam results or orders. The pattern is always the same: clear the old items, then for each piece of data create an element, fill it, and append (add) it to the parent.

javascript
const products = [
  { id: 'p1', name: 'Rice 5 kg', price: 320 },
  { id: 'p2', name: 'Toor dal 1 kg', price: 160 },
];
const list = document.querySelector('#product-list');
list.replaceChildren(); // remove the old items
for (const product of products) {
  const li = document.createElement('li');
  li.textContent = `${product.name} - Rs ${product.price}`;
  li.dataset.id = product.id;
  list.append(li);
}
Rendering a list from an array: create, fill, append
Careful: innerHTML turns a string into real HTML. If that string contains something a user typed, a person could type an <img> tag with an onerror script and run their own code on your page. This attack is called XSS (cross-site scripting). For user data, always use textContent, which shows the text as plain text.
Tip: element.remove() deletes an element from the page. list.replaceChildren() empties a list in one step. Both are supported in every modern browser.

Watch the lesson

The DOM and changing the page · 1/7

JavaScript + DOM = a living page

Today we learn how JavaScript changes a page while you look at it.

Prefer a video by a teacher? Find free videos on “javascript dom manipulation querySelector tutorial for beginners” on YouTube ↗

In real life: An exam results page

On a board exam results site, you type your roll number and press Search. JavaScript finds the empty results table, creates one row for each subject from the data, sets the heading text to the student name with textContent, adds the class "pass" to the result badge, and sets hidden = true on the loading spinner. The page changes without loading a new page.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function setShopStatus(el, isOpen). When isOpen is true, set el.textContent to "Open now" and add the class "open". When it is false, set the text to "Closed" and remove the class "open". The tests give you a fake element with textContent and classList, just like a real one.

Task 2 · Code · Javascript

Write a function renderProducts(list, products, doc) that draws a product list. First empty the list with list.replaceChildren(). Then for each product make an <li> with doc.createElement("li"), set its textContent to "<name> - Rs <price>" (for example "Rice 5 kg - Rs 320"), set li.dataset.id to the product id, and add it with list.append(li). In a real page you would pass document as doc; the tests pass a fake one.

Task 3 · Practice

Build a small "price list" page in your browser. Make an index.html with an <h1 id="shop-name">, an empty <ul id="product-list"> and a script loaded with defer. In app.js, keep an array of 4 or 5 products, change the heading text with textContent, and draw the list with createElement and append. Add a data-id to each <li>, and check it in the Elements panel of DevTools.

Quick quiz

Question 1

1.What is the DOM?

Question 2

2.What does document.querySelectorAll('.item') return?

Question 3

3.Why do we add defer to the script tag in the head?

Question 4

4.An element has data-product-id="p7". How do you read it in JavaScript?

Question 5

5.You want to show a name that a user typed. Which line is safe?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: JSON and working with real data