Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

When Nothing Is Found

What if querySelector() finds nothing, for example because of a typo in the selector? Then it returns null: a special value that means “nothing”.

const price = document.querySelector("#prise");
console.log(price); // Prints: null

null has no properties, so the next line that uses it ends with an error:

console.log(price.textContent);
TypeError: Cannot read properties of null (reading 'textContent')

The message says: I can't read the property textContent of null. When you change the text instead of reading it, the message is a little different: TypeError: Cannot set properties of null (setting 'textContent'). Both mean the same thing: the variable holds null, because the element wasn't found.

The error stops the script: the lines after it don't run. The most common reasons why an element isn't found are:

  • a typo in the selector or in the HTML: "#prise" instead of "#price",
  • a missing # or dot: "price" looks for an element with the tag name price, and there's none,
  • letters that don't match exactly: "#Price" doesn't find id="price", and ".bigPrice" doesn't find class="big-price",
  • the script element isn't at the end of body, so the elements don't exist yet when the script runs.

When you see such an error, print the element with console.log(). If it's null, compare the selector with index.html letter by letter.

Instructions

  1. 1

    The console under the page shows an error. Fix the selector in the first line of script.js, so that the page shows the score 2 : 1.

  2. 2

    Click Run again: now there's another error, because the script got further. Fix the second selector too, so that the last paragraph shows Last goal: Anna.

Back

3/10

  1. 1. JavaScript in a Web Page
  2. 2. Finding Elements
  3. 3. When Nothing Is Found
  4. 4. Changing Styles
  5. 5. Reacting to Clicks
  6. 6. A Click Counter
  7. 7. Text Fields
  8. 8. Creating Elements
  9. 9. Showing an Array
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.