Code / JavaScript from Zero / Unit 5: The DOM and events

Change the page पेज बदलिए

Lesson 11 of 15 · about 14 minutes · querySelector, textContent, classList and click events — a counter app.

⚡ 0 XP

Step 1 of 2

Find an element and change it

bodyh1ul"text"li

The browser turns your HTML into a tree of objects called the DOM. JavaScript can find any element and change it:

  • document.querySelector("#title") finds the element with id="title" (use .name for a class, like CSS)
  • el.textContent = "New text"; changes its text
  • el.classList.add("highlight"); adds a CSS class (also remove and toggle)

Now your code changes what people see. Try it — the preview updates when you run.

Example
const heading = document.querySelector("h1");
heading.textContent = "Jai Hind!";
heading.classList.add("big");

🎯 Challenge: Namaste, India! +15 XP

Use querySelector to:

  1. Change the text of #title to Namaste, India!
  2. Add the class highlight to the paragraph with class msg

Try twice to unlock the solution (0/2)

script.jsCtrl ⏎
Preview
Console

Output from console.log appears here.

Checklist

Press Run to check your code.

  • The title says “Namaste, India!”
  • The paragraph has the class highlight
  • querySelector and textContent are used
Lesson notes (text version)

1. Find an element and change it

The browser turns your HTML into a tree of objects called the DOM. JavaScript can find any element and change it:

  • document.querySelector("#title") finds the element with id="title" (use .name for a class, like CSS)
  • el.textContent = "New text"; changes its text
  • el.classList.add("highlight"); adds a CSS class (also remove and toggle)

Now your code changes what people see. Try it — the preview updates when you run.

                const heading = document.querySelector("h1");
heading.textContent = "Jai Hind!";
heading.classList.add("big");
              

Challenge: Namaste, India!

Use querySelector to:

  1. Change the text of #title to Namaste, India!
  2. Add the class highlight to the paragraph with class msg

2. Events: a counter app

An event is something the user does: a click, a key press, typing. You tell the browser which function to run when it happens:

button.addEventListener("click", () => { ... });

The function runs every time the button is clicked. A counter app keeps a number in a let variable, changes it on each click, and then shows it with textContent.

                let likes = 0;
const btn = document.querySelector("#like");
btn.addEventListener("click", () => {
  likes++;
  btn.textContent = `👍 ${likes}`;
});
              

Challenge: Count the visitors

A gatekeeper counts visitors. +1 already works. Make −1 subtract one (but never go below 0) and Reset set the count back to 0. Always show the new count in #count.

Search by task, format or tool name.