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, Final Project, you'll put together everything you've learned in this course and build a small app step by step.
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
Make the piggy bank work. In script.js, find the elements you need. When the button #save is clicked, add the number typed into #amount to a variable saved (create it with the value 0), and show the total in #saved as Saved: 150 (after saving 100 and 50).
When the total reaches the goal, that is, when it's at least 500, add the class reached to #saved, which makes it green.
Start programming for free
10/10