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

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.

Frank :

Hello,

I have a problem with mi page, i debugged and got this error: "Uncaught TypeError: Cannot set property 'disabled' of null at ImprimeLista".

<redacted by admin />

Ibrahima Diallo :

Hi @Frank

I redacted your message because it was too much code. The error you are getting is exactly what I have described in the article.

It says it cannot set property disabled of null. Where is disabled used? They are the elements with id btConsulta, btDescargar and btHist. In your javascript, they are null because you are calling your script too early, or because the elements are not on the page.

Also, you are using document.write() this will not work for anything that is loaded after the page is rendered.

I hope this helps.

diamond :

function d2O(){var b=document.getElementById("pgLength").value;var f=0;if(document.getElementById("Nosimilar").checked){f=1}var a=0;if(document.getElementById("Symbols").checked){a=1}var a6=0;if(document.getElementById("NoAmb").checked){a6=1}var g=0;if(document.getElementById("Lowercase").checked){g=1}var b7=0;if(document.getElementById("AutoSelect").checked){b7=1}var l=0;if(document.getElementById("Uppercase").checked){l=1}var p=0;if(document.getElementById("Numbers").checked){p=1}var e=document.getElementById("Client").checked;if(e){var o=Em0(b,f,g,l,p,a,a6);var k=cY_(o);document.getElementById("final_pass").value=o;if( b>50 )k="";document.getElementById("PhoneticPronunciation").innerHTML=k;if(b7)s_('final_pass');}

It says there is a problem (Uncaught TypeError: Cannot read property 'checked' of null at d2O). How do I fix it?

Ibrahima Diallo :

First of all, why would you write your code like that? You are making it hard for yourself to debug. Indent your code. Unminify it. Help yourself.

Then read the code. The error is obvious. One of the ids you are trying to get does not exist.

As :

Do you know where the error is? Thanks

document.getElementsByClassName("grade gradient-8-bg")[0].getElementsByTagName("input")[0].value = "ABC";

di :

i get the error code cannot read property "options" of null in my code below :

<!DOCTYPE html>  
<html>  
    <head>  

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
    </head>  
    <body> 

        <br /><br />
        <div class="container" style="margin-top: 100px">            
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div class="row">
                    <div class="col-md-9" style="margin-bottom: 20px; margin-left: 150px">
                        <h2 class="panel-title"><center><b>Data Downtime Machining</b></center></h2>
                    </div>       

                    <label class="col-md-6 control-label" align="left" style="padding-right: 50px""padding-left: 50px">Tanggal</label> 
                    <div class="col-md-6"><select name="Shift" class="form-control" align="Right" style="padding-left: 100px id="Tanggal"> <option value="">Tanggal</option>
                            <?php
                            foreach($resultTgl as $row)
                            {
                                echo '<option value="'.$row["tanggal"].'">'.$row["tanggal"].'</option>';
                            }
                            ?>
                    </select></div>

                    <label class="col-md-6 control-label"align="left" style="padding-right: 50px""padding-left: 50px">Shift</label> 
                    <div class="col-md-6"><select name="Shift" class="form-control" id="Shift">
                                <option value="">Shift</option>
                            <?php
                            foreach($resultShift as $row)
                            {
                                echo '<option value="'.$row["shift"].'">'.$row["shift"].'</option>';
                            }
                            ?>
                    </select>
                    </div>
                    <label class="col-md-6 control-label" align="left" style="padding-right: 50px""padding-left: 50px">Jenis Downtime</label> 
                    <div class="col-md-6">
                            <select name="DT" class="form-control" id="DT">
                                <option value="">Jenis Downtime</option>
                            <?php
                            foreach($resultDT as $row)
                            {
                                echo '<option value="'.$row["DT"].'">'.$row["DT"].'</option>';
                            }
                            ?>
                            </select>
                    </div>
                    <div>
                            <td><button type="button" onclick="cariData()" class="btn btn-primary">Cari</button>
                            </td>
                           <!--  <?php 
                            echo '<form action="" method="POST"<input type="button" value="submit"</form>'; ?> -->
                        </div>
                    </div>
                </div>
                <div class="panel-body">
                    <div id="chart_area" style="width: 1000px; height: 620px;"></div>
                </div>
            </div>
        </div>  
    </body>  
</html>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback();

function cariData(){



    var dropTgl = document.getElementById("Tanggal");
    var dropShift = document.getElementById("Shift");
    var dropDT = document.getElementById("DT");

    var dataTgl = dropTgl.options[dropTgl.selectedIndex].text;
    var dataShift = dropShift.options[dropShift.selectedIndex].text;
    var dataDT = dropDT.options[dropDT.selectedIndex].text;

    //console.log("aaa " + dataTgl + " " + dataShift + " " + dataDT ) ;
    load_data(dataTgl,dataShift,dataDT);

}

jefryarch :

This error occurs when you read a property or call a method on a null object . That's because the DOM API returns null for object references that are blank. An object is expected somewhere and wasn't provided. So, you will get null is not an object error if the DOM elements have not been created before loading the script. In JavaScript , null is not an object; and won't work. You must provide a proper object in the given situation.

We can resolve this type of issues by adding an event listener that will notify us when the page is ready. Once the addEventListener is fired, the init() method can make use of the DOM elements.

document.addEventListener('readystatechange', function() { if (document.readyState === "complete") { init(); }

Michael Wahome :

const colorBtn = document.querySelector('.colorBtn'); const bodyBcg =document.querySelector('body');

const colors=['yellow', 'red','green', '#3b5998'];

colorBtn =addEventListener('click',changeColor);

function changeColor(){ let random=Math.floor(Math.random()*colors.length) bodyBcg.style.backgroundColor =colors(random); }

What is the problem with this line?

colorBtn =addEventListener('click',changeColor);

Gives "Uncaught TypeError:assignment to constant variable"

Anitha Ngarajan :

Hello please help with the uncaught null error in the below:

let divReg = document.getElementById("divRegistered"); 
let divMain = document.getElementById("divMain"); 

document.addEventListener("DOMContentLoaded", function() {      

    divMain.addEventListener("focus", fHandleEnter, true);
    divMain.addEventListener("blur", fHandleExit, true);

fucntions defined later in the code...

The error says that the above:

divMain.addEventListener("focus", fHandleEnter, true);

"Uncaught TypeError: Cannot read property addEventListener' of null"

Thanks!

Azumie :

Hello @Michael Wahome

The problem is that the addEventListener here is placed as a value of the colorBtn variable. That's not how the addEventListener works...

for more information about this: https://www.w3schools.com/JSREF/met_document_addeventlistener.asp

aznan ramin :

Code:

const filterContainer = document.querySelector("portfolio-filter"),
    filterBtns = filterContainer.children,
    totalFilterBtn = filterBtns.length,
    portfolioItems = document.querySelector("portfolio-items").children;
    totalPortfolioItem = portfolioItems.length;
    console.log("totalPortfolioItem");
for (let i = 0; i<totalFilterBtn; i++) {
    filterBtns[i].addEventListener("click",function(){
        this.classList.add("active");
    });
}

uncaught-typeerror-cannot-read-property-of-null,happens for line 4, please tell me what to do?

Shruti Mishra :

Can you please help me solve this error:

https://github.com/shrutimishra1214/error/blob/main/index.html

Find my code here

Chibuzo :

Am getting tired of everything about the error am getting after trying to run my code in javascript. I have being trying to build a quiz app and am get an error "TypeError: Cannot set property 'innerHTML' of null". The more i try to get solution from the internet concerning the problem the more frustrated i become. I created an external js file but all the solution i have been getting were based on internal file. please someone should attend to my problem because its urgent

mukty :

My code:

const form = document.getElementById("form");
const username = document.getElementById("username");
const email = document.getElementById("password");
const password = document.getElementById("password");
const password2 = document.getElementById("password2");


form.addEventListener("submit", e=> {
    e.preventDefault();

    checkInputs();
});




function checkInputs() {
    var usernameValue = username.value.trim();
    var emailValue = email.value.trim();
    var passwordValue= password.value.trim();
    var password2Value = password2.value.trim();

    if(usernameValue === "") {
        setErrorFor(username, "Username cannot be blank");
    } else {
        setSuccessFor(username);
    }

    if(emailValue === "" ) {
        setErrorFor(email, "Not valid email");
    } else {
        setSuccessFor(email);
    }

    if(passwordValue === "") {
        setErrorFor(password, "Password cannot be blank")
    } else {
        setSuccessFor(password);
    }

    if(password2Value === "") {
        setErrorFor(password2, "Password2 does not match");
    } else if(passwordValue !== password2Value) {
        setErrorFor(password2, "Passwords does not match")
    } else {
        setSuccessFor(password2);
    }
}

function setErrorFor(input, message) {
    const formControl = input.parentElement;
    const small = formControl.querrySelector("small");
    formControl.className = 'form-control error'
    formControl.innerText = message;
}

function setSuccessFor(input) {
    const formControl = input.parentElement;
    formControl.className = "form-control success";
}

function isEmail(email) {
    return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}

Please what's wrong with this code...I having the same error message at ##password2Value = password2.value.trim();

Ibrahim :

Hi @mukty

It looks like you are defining the form inputs before the DOM is ready. You can move all your code inside a function that will be called onload (or DOMContentLoaded).

Ex:

function initPage() {
    const form = document.getElementById("form");
    const username = document.getElementById("username");
    const email = document.getElementById("password");
    .... rest of your code ....
}

window.addEventListener("load", initPage, false);

This way, you are accessing the form inputs after they have been loaded on the page.

mukty :

Please I'm trying to a simple validation of an email address that will display an error message when a wrong address is entered. However, I'm having issue displaying the error when the regular expression is used to test the email entered. Below is my code.

HTML:

<div><span id="errorme" style="color:red"></span></div>
<form action="" onsubmit="return click_me()">
    <label>Email:</label><br>
    <input type="email" name="email" id="email"><br>
    <input type="submit" name="submit" value="Submit">
</form>

javascripts code:

function click_me() {
    var email = document.getElementById("email").value.trim();
    var regEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var errorme = document.getElementById("errorme");
    if(email==""){
        errorme.innerHTML="Please enter email";
        return false;
    }else if(!regEmail.test(email)){
        errorme.innerHTML="Invalid email address.";
        return false;
    } else {
        return true;
    }
}

Rafay :

Hello IBRAHIM

Thanks for the Post

I am also facing a similar situation and can't find a answer

Here is my code:

function showNote2() {
    console.log("Show");
    let note = localStorage.getItem("notes");
    if(note == null){
        noteData = []
        // message.innerText = "Please Add a Note"
    }
    else{
        noteData = JSON.parse(note);
    };
    let showBox = "";
    noteData.forEach(function show(element, index) {
        showBox += `<div class="noteCard my-2 mx-2 card" id="card4${index}" style="width: 18rem;">
        <select id="mySelect${index}" class="clr-btn" style="text-align:center" onchange="change_color()">
        <option id="bckgrnd-clr" value="white">Background Color</option>
        <option  value="Red">Red</option>
        <option value="Green">Green</option>
        <option  value="Blue">Blue</option>
        </select>
                <div class="card-body" id="card${index}">
                  <h5 class="cardtitle">Note
                  ${index + 1}
                  </h5>
                  <p class="card-text"> 
                  ${element}
                  </p>
                  <button id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</a>
                </div>
              </div>   `
    })
    let showNote3 = document.getElementById("notes2");
    if(noteData.length != 0){
        showNote3.innerHTML = showBox;
    } else {
        showNote3.innerHTML = "Please add a Note"
    }
    //   Color()
}

I am trying to apply color on each card. My project is a note-taking website.

Here is the code used for applying color on card:

function change_color(index) {
    let note = localStorage.getItem("notes");
    if(note != null ){
        let showNote3 = document.getElementById(`card4${index}`)
        let colorApply = document.getElementById(`card${index}`)
        let elm1 = document.getElementById(`mySelect${index}`)
        elm1.options[elm1.selectedIndex]
        colorApply.style.backgroundColor = color;
    } else {
        `Note is Empty`
    }

The issue is elm1.options line.

Everytime i get this error

"Uncaught TypeError: Cannot read properties of null (reading 'options')"

Thanks

Shohel :

The program is running before the calling fo

document.addEventListener('DOMContentLoaded', Store.displayBooks)!

But when I call Store.displayBooks the error shows:

Uncaught TypeError: Cannot read properties of null (reading 'title')
at Function.addToBookList (script.js:144:24)
at script.js:199:20
at Array.forEach (<anonymous>)
at HTMLDocument.displayBooks (script.js:198:19)

The code:

let form = document.querySelector('#book-form');
let table = document.querySelector('#book-list');

class Book {
    constructor(title, author, isbn) {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
    }
}

class UI {

    static addToBookList(item) {
        let row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.title}</td>
            <td>${item.author}</td>
            <td>${item.isbn}</td>
            <td><a href='#' class = 'delet'>x</a></td>`;
        let table = document.querySelector('#book-list');
        table.appendChild(row);
    }
    static clearFields() {
        document.querySelector('#title').value = '';
        document.querySelector('#author').value = '';
        document.querySelector('#isbn').value = '';

    }
    static deleteBooks(target) {
        if (target.hasAttribute('href')) {
            target.parentElement.parentElement.remove();

            Store.removeBook(target.parentElement.previousElementSibling.textContent.trim());
        }
    }
    static showAlert(message, className) {
        let div = document.createElement('div');
        div.className = `alert ${className}`;
        div.appendChild(document.createTextNode(message));
        let container = document.querySelector('.container');
        let form = document.querySelector('#book-form');
        container.insertBefore(div, form);

        setTimeout(function() {
            document.querySelector('.alert').remove();
        }, 3000);
    }
}

class Store {
    static getTask() {
        let books;
        if (localStorage.getItem('books') === null) {
            books = [];
        } else {
            books = JSON.parse(localStorage.getItem('books'));
        }
        return books;
    }
    static addBookInLs(book) {
        let books = Store.getTask();
        books.push(book);

        localStorage.setItem('books', JSON.stringify(books));
    }
    static displayBooks(e) {
        let books = Store.getTask();

        books.forEach(book => {
            UI.addToBookList(book);

            localStorage.setItem('books', JSON.stringify(books));
        });
    };
    static removeBook(isbn) {
        let books = Store.getTask();

        books.forEach((book, index) => {
            if (book.isbn === isbn) {
                books.splice(index, 1);
            }
        })
        localStorage.setItem('books', JSON.stringify(books));
    }
}

form.addEventListener('submit', addBook);
table.addEventListener('click', deleteBook);
document.addEventListener('DOMContentLoaded', Store.displayBooks);

function addBook(e) {
    let title = document.querySelector('#title').value,
        author = document.querySelector('#author').value,
        isbn = document.querySelector('#isbn').value;

    if (title === '' || author === '' || isbn === '') {
        UI.showAlert('Please fill all the fields', 'error');
    } else {
        let book = new Book(title, author, isbn);

        UI.addToBookList(book);
        UI.clearFields();
        UI.showAlert('Book added', 'success');
        Store.addBookInLs(book);

    }
    e.preventDefault();
}

function deleteBook(e) {
    UI.deleteBooks(e.target);
}

Jeremiah :

Hello ibrahim, I can't find the error in my code. Could you kindly help me? Here is my Javascript code:

const hexColors = ["yellow", "red", "green", "#0081A7", "#FED9B7", "#CAD8DE"];
const btn = document.getElementById("btn");
const color = document.querySelectorAll(".color");

btn.addEventListener("click", function() {
  const randomNumber = 3;
  document.body.style.backgroundColor = hexColors[randomNumber];
  color.textContent = hexColors[randomNumber];
});

With my HTML code:

<main>
    <div class="container">
    <h2>background color : <span class="color">#f1f5f8</span></h2>
    <button class="btn btn-hero" id="btn">click me</button>
    </div>
</main>

Very easy code actually, but I don't find the error. I appreciate your help.

GAYATRI :

I am getting error at line no. 16 as Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length'). can you help solving it.

import React, { useState } from 'react'
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';

const App = () => {

const [myOptions, setMyOptions] = useState([])

const getDataFromAPI = () => {
    console.log("Options Fetched from API")

    fetch('https://jsonplaceholder.typicode.com/users').then((response) => {
    return response.json()
    }).then((res) => {
    console.log(res.json)
    for (var i = 0; i <= res.json.length; i++) {
        myOptions.push(res.json[i].name)
    }
    setMyOptions(myOptions)
    })
}

return (
    <div style={{ marginLeft: '40%', marginTop: '60px' }}>
    <h3>Greetings from GeeksforGeeks!</h3>
    <Autocomplete
        style={{ width: 500 }}
        freeSolo
        autoComplete
        autoHighlight
        options={myOptions}
        renderInput={(params) => (
        <TextField {...params}
            onChange={getDataFromAPI}
            variant="outlined"
            label="Search Box"
        />
        )}
    />
    </div>
);
}

export default App

Ibrahim Diallo :

Hi @Gaytari

You just have to remove the .json on line 16 because res is the json object.

fetch('https://jsonplaceholder.typicode.com/users')
.then((res) => res.json())
.then((res) => {
    for (var i = 0; i < res.length; i++) {
        myOptions.push(res[i].name)
    }
    setMyOptions(myOptions)
});

Good luck

OSMmapper :

I am trying to display a polygon on OSM:

$.get('./load-polygon.php', 
function(csvString) {

map.eachLayer(function (layer)
{
    if (layer instanceof L.Polygon)
    {
        layer.remove();
    }
});

var data = Papa.parse(csvString, {header: true, dynamicTyping: true}).data;

for (var i in data)
{
    var row = data[i];
    var polygon = L.polygon([row.Polygon], {color: '#ff4f00'}).addTo(map);
}

});

In the console row.Polygon shows the correct values but I still get the following error:

Uncaught TypeError: Cannot read properties of null (reading '0') at i.projectLatlngs (leaflet.js:5:79693) at i.projectLatlngs (leaflet.js:5:79838) at i.projectLatlngs (leaflet.js:5:79838) at i.project (leaflet.js:5:79369) at i.reset (leaflet.js:5:75435) at i.onAdd (leaflet.js:5:74837) at i.layerAdd (leaflet.js:5:63932) at i.whenReady (leaflet.js:5:42041) at i.addLayer (leaflet.js:5:64307) at i.addTo (leaflet.js:5:63275)

Can you please help me?

Valeri :

Regards. Excellent article is short and easy to read. I can understand what are my problem in my code. Thank you

yeli :

I just wanna know what is wrong in this code

mostrarServicios(stockPlanes)

function mostrarServicios(array) {
    array.forEach(item => {
        let div = document.createElement('div')
        div.classList.add('planes')
        div.innerHTML += `
                <div class="card">
                <div class="card-image">
                <img src=${item.img}>
                <span class="card-tittle">${item.nombre}</span>
                <a id="sumar${item.id}"class="btn-floatin halfway-fab waves-effect waves-light red"><i class="material-icons">add</i></a>
                </div>
                <div class=" card-content">
                <p>${item.desc}</p>
                <p>PRECIO: $${item.precio}</p>
                </div>
                </div>`;

        contenedorServicios.appendChild(div)

        let btnSumar = document.getElementById(`sumar${item.id}`)
        console.log(btnSumar)

        btnSumar.addEventListener('click', () => {
            console.log(item.id);
            sumarAlCarrito(item.id);
        });
    });
}

function sumarAlCarrito(id) {
    let serviciosSumar = stockPlanes.find(elemento => elemento.id == id)
    carritoDeServicios.push(serviciosSumar)
    mostrarCarrito(serviciosSumar)

    /* 
    cause i got this mistake:

    app.js: 94
    Uncaught TypeError: Cannot read properties of null(reading 'appendChild')
    at mostrarCarrito(app.js: 94: 23)
    at sumarAlCarrito(app.js: 74: 4)
    at HTMLAnchorElement. < anonymous > (app.js: 54: 10)
    Show 3 more frames
    */
}

function mostrarCarrito(serviciosSumar) {
    let div = document.createElement('div')
    div.className = 'serviciosEnCarrito'
    div.innerHTML = `
                <div class="serviciosEnCarrito">
                <p>${serviciosSumar.nombre}</p>
                <p>$${serviciosSumar.precio}</p>
                <p id="Und ${serviciosSumar.id}">Und:${serviciosSumar.cantidad}</p>
                </div>
                <button id="eliminar${serviciosSumar.id}" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                <button type="button" class="btn btn-primary">Guardar Cambios</button>    
    `
    contenedorCarrito.appendChild(div)
}

Ibrahim Diallo :

Hi @yeli

It looks like your variable contenedorServicios is null. Look for the place where you define it. It's possible you defined it before the DOM was ready.

Let's hear your thoughts

For my eyes only