JavaScript Basics · Lesson 11 of 13

Changing the Page

Until now your code only printed to the console. JavaScript's real home is the web page, where it can read and change everything you see.

The browser gives your code an object called document that represents the page. People call this the DOM (Document Object Model). You do not need the name, only the idea: every element on the page is an object you can get hold of.

Finding an element

document.querySelector takes a CSS selector and returns the first element that matches:

const title = document.querySelector("h1");
const box = document.querySelector("#message");   // by id
const card = document.querySelector(".card");     // by class

The selectors are the same ones you use in CSS: a tag name, # for an id, . for a class.

Changing it

Once you have the element in a variable, change its properties:

title.textContent = "Welcome back!";
title.style.color = "tomato";
box.style.backgroundColor = "gold";
  • textContent is the text inside the element.
  • style holds its CSS. Property names with a dash are written in camelCase here: background-color becomes backgroundColor.

Classes

Often it is cleaner to prepare a class in CSS and switch it on from JavaScript:

box.classList.add("highlight");
box.classList.remove("highlight");
box.classList.toggle("highlight");   // on if off, off if on

The editor now has an index.html tab and a script.js tab. The script runs after the page has loaded, and the preview shows the result. console.log still works and appears under the preview.

Your Task

  1. In script.js, find the element with the id status and store it in a variable.
  2. Change its text to exactly Open now.
  3. Change its text color to green.
  4. Find the <h1> and add the class big to it.
  • The script uses document.querySelector (or getElementById)
  • The status paragraph says Open now
  • The status text is green
  • The heading has the class big