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(18)

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.

Shahnila Fahmi :

Cannot read property 'salt' of null at aes.js

kelvin :

<!DOCTYPE html>
<html lang="en">
<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">
    <!-- <script src="javascript/jquery-3.4.1.min.js"></script> -->
    <!-- <script src="bootstrap-4.3.1-dist/js/bootstrap.js"></script> -->
    <!-- <link rel="stylesheet" href="bootstrap-4.3.1-dist/css/bootstrap.css"> -->
    <link rel="stylesheet" href="stylesheet/style.css">
    <script src="GNG.js"></script>
    <!-- <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet"> -->
    <title>GnG</title>
</head>
<body>
    <nav>
        <div class="navbar-brand">
            George n George
        </div>
        <!-- <a class="navbar-brand" href="#"></a> -->
        <ul class="nav-links">
            <li class= "nav-active"  ><a href="#">Home </a></li>
            <li ><a href="#">Contact</a> </li>
            <li ><a href="#">About us</a></li>
            <li ><a href="#">Laundry</a></li>
            <li ><a href="#">Clothes </a></li>
            <li ><a href="#">Business</a></li>
        </ul>
        <div class="burger">
            <div class="line1"></div>
            <div class="line2"></div>
            <div class="line3"></div>
        </div>
    </nav>

</body>
</html>


const navSlide = () => {
    const burger = document.querySelector('.burger');
    const nav = document.querySelector('.nav-links');
    // const navLinks = document.querySelectorAll('.nav-links li');

    burger.addEventListener('click', () =>
    {
        nav.classList.toggle('nav-active');
        navLinks.forEach((link, index) =>
        {
            link.style.animations = `navLinkFade 0.5s ease forward ${ index / 7 + 1.5 }s`;

        });
    });
}

navSlide();

please why im i getting this error:

Uncaught TypeError: Cannot read property 'addEventListener' of null

NOTE: i have a css file that corresponds with the animation code i the js file

Ibrahima Diallo :

Hi Kelvin

Looking at your code, I assume that the javascript you wrote is in GNG.js. Right?

The issue is you are running your script before the page is done downloading. So when you call document.querySelector('.burger'); inside GNG.js, the html element with class burger doesn't exist yet. You have to wait for the DOM (Document object model) to be ready before you can access it. Since you have jQuery on the page, you can do that by wrapping your code in a Jquery Function. Example:

$(function() { // this runs when the dom is ready.
    const navSlide = () => {
    const burger = document.querySelector('.burger');
    const nav = document.querySelector('.nav-links');
    // const navLinks = document.querySelectorAll('.nav-links li');
    burger.addEventListener('click', () => {
        nav.classList.toggle('nav-active');
        navLinks.forEach((link, index) => {
            link.style.animations = `navLinkFade 0.5s ease forward ${ index / 7 + 1.5 }s`;
        });
    });
    navSlide();
}); // end of jQuery DOM Ready function

Try it out and let me know if it works.

Renan :

Please, where is the error at the following code?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <select name="sel" onchange="show(this)">
            <option value="">-- Select --</option>
        </select>
        <p id="demo"></p>
        <p>
        <input type="button" 
               style="margin:10px 0;" 
               onclick="popularCombo()" 
               value="Click to Populate SELECT with JSON" />
        </p>
        <!--<div id="iii">

        </div>
        <input type="button" value="BUSCAR" onclick="buscarTexto();" />-->
    </body>
    <script type="text/javascript">
    function buscarTexto(){
        alert('oi');

        document.getElementById('iii').innerHTML="esse <br><p><span>xkjkalskjklasjklasj</span> ssssssssssss<font size='20' color='red'>sssssss</font>ssssssaaaaaaaaaaaaaaa a a a a a a <span>dddddddd</span></p></br>";

        var taElements = document.getElementById('iii').querySelectorAll('span');

        for(i=0;i<taElements.length;i++){
            taElements[i].style.backgroundColor="cyan";
        }               
    }

    window.onload = (function() {
        popularCombo()
    });

    function popularCombo() {
        var select = document.createElement("select");
        var ele = document.getElementById('sel');
        alert(ele);
        var obj = JSON.parse('{ "tab" : "00000001", "descr" : "Identificacao do Sexo", "itens" : [ { "value" : "FEMININO", "key" : "F" }, { "value" : "MASCULINO", "key" : "M" } ] }');       // JSON a parsear

        for (var i = 0; i < obj.itens.length; i++) {
            var option = document.createElement("option");
            option.key = obj.itens[i].key;
            option.value = obj.itens[i].value;
            select.appendChild(option);
            console.log(option.value);
            ele.innerHTML = ele.innerHTML + '<option value="' + obj.itens[i]['key'] + '">' + obj.itens[i]['value'] + '</option>';
            //document.getElementById("demo").innerHTML = option.value;
        }

    }

    function show(ele) {
        // GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
        var demo = document.getElementById('demo');
        demo.innerHTML = 'Sexo Selecionado: <b>' + ele.options[ele.selectedIndex].text + '</b> </br>' +
            'key: <b>' + ele.value + '</b>';
    }
    </script>
</html>

Renan :

Found the bug, thanks! Sorry, once again, for the mess.

Ibrahima Diallo :

No worries @Renan I fixed the formatting. Also I'm glad that you also found a solution.

For anyone else wondering in the future, the error was;

Uncaught TypeError: Cannot read property 'innerHTML' of null

Meaning,the element with id iii did not exist. The reason was that Renan had added an HTML comment around that element.

Thank you for contributing.

Renan :

Yes, man, actually, the 'main' bug that was bothering me was in call the "popularCombo" function. There, I got the exception by passing the line

ele.innerHTML = ele.innerHTML +' <option value = "'+ obj.itens [i] [' key '] +'"> '+ obj.itens [i ] ['value'] + '</option>'; 

because var 'ele' used a 'sel' parameter that didn't exist (the combobox I did had a name = "sel" parameter, not id). I don't know if I make myself clear, but that's what happened! Hehe.

Thanks!

Alan :

It is my code can you tell me where is the error:

<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
    function sum()
    {
        var ans,num1,num2;
        num1 = document.frmcalc.txtnum1.value;
        num2 = document.frmcalc.txtnum2.value;

        ans=num1+num2;
        document.frmcalc.txtans.value=ans;
    }
</script>
</head>
<body>
    <center>
        <form name="frmcalc">
        number 1
        <input type="text" name="textnum1"><br>
        number 2
        <input type="text" name="textnum2"><br>
        answer 
        <input type="text" name"textans"><br>
        <input type="button" value="+" onclick="sum()">
        </form>
    </center>

</body>
</html>

Ibrahim Diallo :

Hi Alan. You misspelled textnum1, txtnum2 and textans. Instead you are missing the e. and You forgot the = sign in name"textans". it should be name="textans".

When all this is fixed, you'll realize that your code doesn't work. If you enter the values 1 and 2, the answer will be 12. The reason is you are adding strings together. You need to change the values to numbers. In your case, use parsefloat. Here is what your code will look like.

function sum() {
    var ans,num1,num2;
    num1 = document.frmcalc.textnum1.value;
    num2 = document.frmcalc.textnum2.value;
    ans = parseFloat(num1) + parseFloat(num2);
    document.frmcalc.textans.value=ans;
}

Good luck.

Schady :

every time i try to run this, it shows up saying "Cannot read property 'id' of null" can somebdody help me please?

I am using visual studio code by the way if that helps

case 'mute': 
    let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
    if(!person) return message.reply("I couldnt locate that member.");

let mainrole = message.guild.roles.find(role => role.name === "Beginners");
let muterole = message.guild.roles.find(role => role.name === "Muted");

if(!muterole) return message.reply("I couldn't find a mute role. Please make sure that there is one under the name Muted.");

let time = args[2];

if(!time){
    return message.reply("Error. Make sure you specified how long you want the person to be muted!");
}

person.removeRole(mainrole.id);
person.addRole(muterole.id);   

message.channel.send(`@${person.user.tag} mas now been muted for ${ms(ms(time))}.`);

setTimeout(function(){
    person.addRole(mainrole.id);
    person.removeRole(muterole.id);
    message.channel.send(`@${person.user.tag} has been unmuted.`)
}, ms(time));
break;

Ibrahima Diallo :

Hi Schady

You checked if muterole is valid, but you haven't checked the value of mainrole. Just add the following.

if(!mainrole) return message.reply("missing main role.");

Note that you have to try to debug your code. Use console.log(variable) to find what is currently in your variables.

Good Luck.

Schady :

alright i put in the code and im debugging it now. thanks for your help!

Fatima Martinez :

Hi!

I'm new on web developing and i'm very bad on scripts... I got the same error: “Uncaught TypeError: Cannot read property 'submit' of null”... Does anybody knows which is the error?

<script type="text/javascript">
    function checkFormRegistroPestaña() {
        if (!esValido("descripcionDocumento", "TEXTO", false)) {
            return false;
        }
        if (!esValido("urlDocumento", "TEXTO", false)) {
            return false;
        }   
        return true;
    }
      function importarDoc(){
//      document.getElementById("accion").value = "importar";
        document.getElementById("operacion").value = "importarDoc";
        document.getElementById("frmImport").submit();
//          _esperando();
       }
        function inicio(){

        }
</script>

<cmz:panel>
    ...
    <form id="frmImport" name="frmImport" action="documento" method="post" enctype="multipart/form-data">
        <input id="operacion" name="operacion" type="hidden" value="" />
        <input id="importCorrecto" name="importCorrecto" type="hidden" value="" />

        <table cellpadding="2px" cellspacing="2px" border="0px">
            <tr>
                <td><cmz:etiqueta titulo="Descripción" />:</td>
                <td colspan="3"><cmz:campoTexto id="descripcionDocumento"
                        valor="${documento.descripcion}"
                        editable="${formularioContrataciones.formularioPestañaActiva.editable}"
                        soloLectura="${!formularioContrataciones.formularioPestañaActiva.editable}"
                        anchura="320px" longitudMaxima="100" requerido="true"></cmz:campoTexto>
                </td>
            </tr>
            <tr>
                <td><cmz:etiqueta titulo="Fichero" />:</td>
                <td><input type="file" id="documento" name="fichero" class="campo"></td>
                <td><cmz:boton onclick="importarDoc();" valor="Importar" id="btnImportar">Importar</cmz:boton></td>
            </tr>
        </table>
    </form>
</cmz:panel>

ibrahim :

Hi Fatima

It looks like the code you posted is not the generated html. Run your code on the browser and check the page source. You can also check on the console (Press F12 to open the console).

Since I cannot run your code, all I can recommend is to take the time to debug. What the error is telling you is that the form with id frmImport does not exist. There could be too many reasons for this. But let's rewrite importarDoc() like this:

function importarDoc(){
    var operacion = document.getElementById("operacion");
    var form = operacion.form;
    operacion.value = "importarDoc";
    form.submit();
}

I hope this helps.

Let's hear your thoughts

For my eyes only