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 as id (a unique name) and class (the name of a group).
  • The page loads a script with <script src="script.js"></script> at the end of body, 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 returns null, and using it ends with an error such as TypeError: Cannot read properties of null (reading 'textContent').
  • textContent is the text of an element; you can read it and change it.
  • element.style.color = "red" changes one style (CSS names in camelCase, such as backgroundColor); classList.add(), remove() and toggle() 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 let variable, items in an array); a handler changes them and shows them on the page again.
  • input.value is the text in a field; Number() turns it into a number.
  • document.createElement("li") creates an element and list.append(item) puts it into the page. To show an array, clear the list with list.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

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

10/10