Finding Elements
To change something on the page, JavaScript first has to find the element. The whole page is available in JavaScript as document, and its method document.querySelector() finds an element for you. Let's try it on this page:
<h1>My Cat</h1>
<p id="cat-name">Mia</p>
<p class="note">She loves to sleep.</p>In the parentheses, you give querySelector() a selector in quotes, which says what to look for:
"h1"finds an element by its tag name, here the main heading,"#cat-name"finds the element with the attributeid="cat-name"(#means id),".note"finds an element with the attributeclass="note"(the dot means class).
An id is a unique name: only one element on the page may have it. A class is the name of a group: several elements can share it, for example so that they look the same. If several elements match the selector, querySelector() returns the first one. CSS uses the same selectors to say which elements a style applies to.
Save the element in a variable, so that you can work with it. console.log() prints an element as its HTML:
const heading = document.querySelector("h1");
console.log(heading); // Prints: <h1>My Cat</h1>We use const, because the variable will always hold the same element, even when we change the element's text.
The text of an element is in its property textContent. You can read it, and you can change it by assigning a new value, which changes the page right away:
const catName = document.querySelector("#cat-name");
console.log(catName.textContent); // Prints: Mia
catName.textContent = "Luna";
console.log(catName.textContent); // Prints: LunaThe page now says Luna instead of Mia. JavaScript changes only the page in the browser, not the file index.html: when the page loads again, it starts from index.html, and the script makes its changes again.
Watch out: the # and the dot belong only in the selector. In HTML, write id="cat-name", in JavaScript "#cat-name".
Instructions
script.js prints the text of the heading. Below that, find the paragraph with the id city, save it in a variable city and change its text to Paris.
Find the paragraph with the class forecast, save it in a variable forecast and change its text to Sunny.
Find the paragraph with the id summary and change its text to the city and the forecast with a colon between them: Paris: Sunny. Don't type the words yourself: read them from city and forecast with textContent, for example in a template literal.
Start programming for free
2/10