TalentJR

🟨 JavaScript tutorial for beginners · Class 8 · Lesson 4 of 18 · Free

DOM Manipulation – Change a Web Page with JavaScript

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Select parts of a page with querySelector and getElementById
  • Change text, styles and classes of elements with JavaScript
  • Create new elements and add them to a live page

The school notice board website still says "Sports Day: TBA" a week after the date was fixed. Someone must edit the page by hand every time. With DOM manipulation, JavaScript can change any text, colour or list on the page in a blink — no reload needed.

What is the DOM in JavaScript?

When a browser loads a page, it turns the HTML into a tree of objects. This tree is the DOM — the Document Object Model. Each tag, like <h1> or <p>, becomes an element in the tree.

JavaScript can reach the whole tree through the word document. Find an element, and you can read it or change it.

document.querySelector() takes a CSS selector: "#id" for an id, ".name" for a class, or a tag name like "h1". It returns the first match.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Sports Day
Date: TBA
H1

💡 Try it: change ".info" to "p:last-of-type" to pick the last paragraph instead.

How do I change text on a web page with JavaScript?

Set textContent to put new text inside an element. The page updates at once.

innerHTML is similar, but it reads tags too. Use it only when you need tags like <b>. For plain text, textContent is safer: if a user types <script> into a box, textContent shows it as text instead of running it.

You can also join onto the old text with +=.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Sports Day: 15 January
Wear your house T-shirt. Reporting time 8:00 am.

💡 Notice: after += with textContent, the bold is gone — textContent keeps only the text.

How do I select many elements at once in JavaScript?

getElementById("marks") finds the one element with that id. Note: no # here, because the method already knows it is an id.

querySelectorAll() returns a list of every match. You go through the list with for...of, which runs the same code once for each item. (Loops come fully in Lesson 9.)

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Subjects: 3
✔ Maths: 88
✔ Science: 92
✔ English: 79

How do I change CSS styles with JavaScript?

Every element has a style property. CSS names with a dash become camelCase in JavaScript: background-color becomes backgroundColor, font-size becomes fontSize.

A cleaner way is to keep styles in CSS and switch a class with classList. add() puts a class on, remove() takes it off, toggle() flips it.

Here the CSS for .lit is written in the <style> part of the page.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
lamp lit
false

💡 Try it: light the middle lamp too. lamps[1] is the second lamp, because counting starts at 0.

How do I add a new element to a page with JavaScript?

Three steps: make it with document.createElement("li"), fill it with textContent, then put it on the page with appendChild().

Until you call appendChild, the new element is only in memory. The animation below shows these steps one by one, before anything is on a page.

🎬 How JavaScript thinks — step 1 of 7JavaScript is about to run line 1
▶const period = document.createElement("li");
2console.log(period.outerHTML);
3
4period.textContent = "Maths";
5console.log(period.outerHTML);
6
7period.classList.add("today");
8console.log(period.outerHTML);
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
<li></li>
<li>Maths</li>
<li class="today">Maths</li>

How do I build a list on a web page with JavaScript?

Now put it together. A function makes one <li> for a period and adds it to the timetable. Calling it four times builds the list.

remove() takes an element off the page. Here the free period is removed at the end.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Periods: 3

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

const p = document.createElement("p");
p.textContent = "Hi";
p.textContent += "!";
p.textContent += "!";
console.log(p.textContent);

Question 2. What does this print?

const box = document.createElement("div");
box.classList.add("big");
box.classList.toggle("big");
box.classList.toggle("red");
console.log(box.className);

Question 3. What does this print?

const b = document.createElement("b");
b.textContent = "<i>Wow</i>";
console.log(b.innerHTML);

🧩 Your challenge

Fill in a report card page. Set the student's name, add one <li> per subject from the given marks, and make the result line green with the text "Result: PASS". Also log what you did. Expected console output: Name: Anaya Rao Subjects added: 3 Result: PASS

Expected output in the console:
Name: Anaya Rao
Subjects added: 3
Result: PASS
🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it

⚠️ Common mistakes (and how to fix them)

❌ Wrong

const score = document.querySelector("score");
score.textContent = "Score: 10";

TypeError: Cannot set properties of null (setting 'textContent')

✅ Right

const score = document.querySelector("#score");
score.textContent = "Score: 10";
console.log(score.textContent);

querySelector needs CSS selectors: "#score" for an id. Without #, it looks for a <score> tag, finds nothing and returns null.

❌ Wrong

const tips = document.querySelectorAll(".tip");
tips.textContent = "Done!";
console.log("Changed the tips");

No error, but nothing on the page changes. querySelectorAll gives a list, and setting textContent on the list does nothing.

✅ Right

const tips = document.querySelectorAll(".tip");
for (const tip of tips) {
  tip.textContent = "Done!";
}
console.log("Changed the tips");

Go through the list with for...of and change each element.

❌ Wrong

const title = document.querySelector("#title");
title.style.font-size = "40px";

SyntaxError: Invalid left-hand side in assignment

✅ Right

const title = document.querySelector("#title");
title.style.fontSize = "40px";
console.log(title.style.fontSize);

In JavaScript a dash means minus, so font-size breaks the line. CSS names become camelCase: fontSize, backgroundColor.

📌 Remember

  • The DOM is the browser's tree of page elements; JavaScript reaches it through document.
  • querySelector("#id" / ".class" / "tag") finds the first match; querySelectorAll finds all.
  • textContent changes text safely; innerHTML also reads tags.
  • style.camelCase changes one style; classList.add/remove/toggle switches CSS classes.
  • createElement + textContent + appendChild adds new things; remove() takes them away.

Finished the quiz and the challenge?

Questions students ask

What is the DOM in JavaScript?

The DOM (Document Object Model) is how the browser stores a page in memory: a tree of elements made from the HTML. JavaScript can read and change this tree, and the page on screen updates straight away.

What is the difference between textContent and innerHTML?

textContent reads and writes plain text only. innerHTML reads and writes HTML, so tags like <b> work. Use textContent for anything a user typed, because innerHTML could run harmful code hidden in their text.

Should I use getElementById or querySelector?

Both work. getElementById("x") is only for ids and needs no #. querySelector("#x") accepts any CSS selector, so many people use it for everything.

Why does querySelector return null?

It found no matching element. Check the spelling, the # or . at the start, and that the HTML element exists before your script runs.