Summary
In this lesson, you learned that:
- A page is written in HTML and made of elements, written with tags:
<h1>Title</h1>. Elements can have attributes, such asid(a unique name) andclass(the name of a group). - The page loads a script with
<script src="script.js"></script>at the end ofbody, so that the elements exist when the script runs. The script runs when the page loads; what it prints and its errors appear in the console under the page. document.querySelector()finds the first element that matches a selector:"h1","#id"or".class". When nothing matches, it returnsnull, and using it ends with an error such asTypeError: Cannot read properties of null (reading 'textContent').textContentis the text of an element; you can read it and change it.element.style.color = "red"changes one style (CSS names in camelCase, such asbackgroundColor);classList.add(),remove()andtoggle()add and remove classes from the page's CSS.button.addEventListener("click", function () { ... })runs the function on every click. Pass the function itself, without().- The data lives in variables (a counter in a
letvariable, items in an array); a handler changes them and shows them on the page again. input.valueis the text in a field;Number()turns it into a number.document.createElement("li")creates an element andlist.append(item)puts it into the page. To show an array, clear the list withlist.textContent = ""and create one item for each element in a loop.
In the next lesson, Events and Forms, your pages will react to more than clicks: to typing, to choosing from a list, to pressing keys and to sending forms.
But first, a little practice: a piggy bank that adds up your savings. This time, script.js is empty, and you'll write the whole program yourself.
Instructions
- 1
Make the piggy bank work. In
script.js, find the elements you need. When the button#saveis clicked, add the number typed into#amountto a variablesaved(create it with the value0), and show the total in#savedasSaved: 150(after saving 100 and 50). - 2
When the total reaches the goal, that is, when it's at least
500, add the classreachedto#saved, which makes it green.