Learn/HTML, CSS & JS/7. JavaScript and the page
Lesson 7 of 8
Sign in

HTML, CSS & JS, lesson 7

JavaScript and the page

JavaScript makes pages react. In the browser it can read and change the page through the DOM (Document Object Model), a tree of objects that mirrors your HTML.

Finding elements

querySelector takes the same selectors as CSS, so "#total", ".card p" and "li" all work. It returns null if nothing matches.

Changing elements

Prefer textContent for text. It treats what you give it as plain text, so a user can't inject HTML into your page.

Events

Pages run your code when something happens: a click, a key press, a form submit. Attach a function with addEventListener:

The function you pass is called every time the event fires. Variables declared outside it, like , keep their values between clicks.

One exercise to try what you just read.

Exercise 1

Pancake counter

Press Ctrl Enter or Check to test your code.

likes

For forms, listen for "submit" on the <form> and call event.preventDefault() to stop the browser from reloading the page.

Further reading

  • MDN: Manipulating documents
  • MDN: Introduction to events
  • MDN: Element.classList

Make the counter work:

  • Clicking #add increases the number shown in #count by 1.
  • Clicking #reset sets it back to 0.
  • When the count reaches 3 or more, add the class full to #count, and remove it again on reset.
const title = document.querySelector("h1");          // first match
const buttons = document.querySelectorAll("button"); // every match
title.textContent = "Order received!";
title.classList.add("done");       // also .remove(), .toggle(), .contains()
title.style.color = "green";       // inline style, best for one-off changes
const button = document.querySelector("#like");
let likes = 0;

button.addEventListener("click", () => {
  likes += 1;
  button.textContent = `Likes: ${likes}`;
});