JavaScript

Uncaught TypeError: Cannot read property of null

TL;DR;


There are a few variations of this error depending on the property you are trying to access. Sometimes instead of null it will say undefined. An example will be:

Uncaught TypeError: Cannot read property 'value' of null

Uncaught TypeError: Cannot read property 'innerHTML' of null

All this means is that you are trying to access a property of an object that is undefined. These usually happens when we don't test an object before using it. Here is a common scenario.

// We want to get the value of an input. 
var inputVal = document.getElementById("input").value;

This will result in Uncaught TypeError: Cannot read property 'value' of null. The reason will be that the element with id input does not exist. Let me break it down in simpler steps;

var input = document.getElementById("input"); 
input // when this fails, it returns null. input = null
var inputVal = input.value;
// this is the same as the following. 
var inputVal = null.value;
// null does not have the property 'value'

When you break it down, the error actually makes sense. To make sure that you don't get this error, you have to make sure that btn, or any object you use, is not null before you use it. For our example:

var input = document.getElementById("btn");
var inputVal = "";
if (input) {
    inputVal = input.value;
}

Sometimes, your object is nested deeper like Tree.folder.path. You just have to make sure that if you need to access folder, than Tree has to be defined. And if you need to access path, then folder needs to be defined.

In some cases, this error is a symptom of another issue. Why would getElementById return null if the element actually exists on the page? Probably because the function is called before the DOM is ready. Always be careful when accessing a DOM element before it is ready.


Comments(4)

Denisander Vivan :

Please, tell me where are de error.

<!DOCTYPE html>
<html lang="pt-br>
    <head>
        <meta charset= "utf-8">
    <title>Detran</title>
        <style>

        </style>
    </head>
    <body>
    <h1>Sistema de multa</h1>
    Velocidade do carro<input type="Number" name="txtvel" id="txtvel"> km por hora
        <input type="button" value="Verificar" onclick = "calcular()">
             <div id="res"> 
            </div>
    <script>
        function calcular() {
            var txtv = window.document.getElementById("txt#vel")
            var resp = window.document.querySelector("div#res")
            var vel = Number(txtv.value)
            resp.InnerText = `Sua velocidade atual é de ${vel}`
        }
    </script>
    </body>
</html>

Ibrahim :

You have an error in this line:

var txtv = window.document.getElementById("txt#vel")

Your correct id is txtvel but you wrote txt#vel. Change it to:

var txtv = window.document.getElementById("txtvel")

You also have an error here resp.InnerText. The correct way is with a lowercase i. Like this: resp.innerText

Also you didn't close the double quotes on your lang attribute in the html tag:

<html lang="pt-br> should be <html lang="pt-br">

Good luck

Ícaro :

Where's the error? Please Help.

HTML

<!DOCTYPE html>
<html>
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="../../CSS/mainStyle.css">
    <link rel="shortcut icon" type="image/x-png" href="../../IMAGES/NumberAnalyzer/logo.png">
    <script src="../../JS/NumberAnalyzer/script.js"></script>
    <title>Number Analyzer</title>
    </head>
    <body>
    <header>
        <h1>Number Analyzer</h1>
    </header>
    <section>
        <div>
            Number within 1 - 100:
            <input type="number" name="number" id="number" class="inputs">
            <br><br>
            <input type="button" value="Add" class="button" onclick="appendList()">
            <br><br>
            <select name="list" id="list" size="10"></select>
            <br><br>
            <input type="button" class="button" value="Finish" onclick="finish()">
        </div>
        <div id="result"></div>
    </section>
    <footer>
        <p>&copy; Ícaro Silva</p>
        <p id="purpose">all of that's just for study, thanks</p>
    </footer>
    </body>
</html>

Javascript

var number = document.getElementById('number')
var list = document.getElementById('list')
var result = document.getElementById('result')
var values = []

function appendList() {
    if(isNumber(number.value) && !isInList(number.value, values)) {
    values.push(Number(number.value))
    let item = document.createElement('option')
    item.text = `Value ${number.value} added`
    list.appendChild(item)
    result.innerHTML = ''
    } else {
    window.alert('Error! Invalid Value or Value already in the list.')
    }
    number.value = ''
    number.focus()
}

function finish() {
    if(values.length == 0) {
    window.alert('Error! Add Values before finish.')
    } else {
    let total = values.length
    var bigger = values[0]
    var smaller = values[0]
    var sum = 0
    for(let index in values) {
        sum += values[index]
        if(values[index] > bigger) bigger = values[index]
        if(values[index] < smaller) smaller = values[index]
    }
    let average = sum / total
    result.innerHTML = ''
    result.innerHTML += `<p>In total we have ${total} numbers registered.</p>`
    result.innerHTML += `<p>The highest reported value is ${bigger}.</p>`
    result.innerHTML += `<p>The lowest reported value is ${smaller}.</p>`
    result.innerHTML += `<p>Adding up all the values, we got ${sum}.</p>`
    result.innerHTML += `<p>The average of reported values is ${average}.</p>`
    }
}

function isNumber(numberval) {
    if(Number(numberval) >= 1 && Number(numberval) <= 100) return true 
    else return false
}

function isInList(numberval, array) {
    if(array.indexOf(Number(numberval)) != -1) return true
    else return false
}

Ibrahim :

The problem is that you haven't debugged your code. You can never find an answer like this. Instead, ask yourself these questions:

  • What is the error?
  • Where is the error?
  • What is the expected behavior?
  • What is the current behavior?

These questions will not only help you find the solution, it will also help you get some help.

Let's hear your thoughts

For my eyes only