Intermediate · JavaScript in the browser: DOM and events · topic 35 of 64 · 30 min
The DOM and changing the page
Explanation
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.
<body>
<h1 id="shop-name">Sharma Kirana</h1>
<ul id="product-list">
<li>Rice</li>
<li>Sugar</li>
</ul>
</body>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.
<head>
<meta charset="utf-8">
<title>Sharma Kirana</title>
<script src="js/app.js" defer></script>
</head>Finding elements
| Method | What it gives you | Example |
|---|---|---|
| document.querySelector(css) | The first matching element, or null | document.querySelector('#shop-name') |
| document.querySelectorAll(css) | A list (NodeList) of all matches; loop with for...of | document.querySelectorAll('.product') |
| document.getElementById(id) | The element with that id, or null | document.getElementById('cart') |
| element.closest(css) | The nearest parent (or itself) that matches | button.closest('li') |
Changing what you found
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 elementdataset 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.
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);
}Watch the lesson
The DOM and changing the page · 1/7
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)
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.
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.
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
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.