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: nullnull 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 nameprice, and there's none, - letters that don't match exactly:
"#Price"doesn't findid="price", and".bigPrice"doesn't findclass="big-price", - the
scriptelement isn't at the end ofbody, 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
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.
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.
Start programming for free
3/10