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";
textContentis the text inside the element.styleholds its CSS. Property names with a dash are written in camelCase here:background-colorbecomesbackgroundColor.
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
- In
script.js, find the element with the idstatusand store it in a variable. - Change its text to exactly
Open now. - Change its text color to
green. - Find the
<h1>and add the classbigto it.
- The script uses
document.querySelector(orgetElementById) - The status paragraph says
Open now - The status text is green
- The heading has the class
big