简体   繁体   中英

"Uncaught TypeError: Cannot read property 'length' of null JAVASCRIPT

I am using simple length function to check length greater than zero based on id. Code i am using is

if ($('#abcd').length > 0)
{
    var abcd = $('#abcd').val();
}

This code is working fine and producing no error. But if i am using simple javascript in this way

if (document.getElementById('abcd').length > 0)
{
    var abcd = document.getElementById('abcd').val();
}

Then it is not working and producing this error "Uncaught TypeError: Cannot read property 'length' of null". What does this error mean and how can i get this working?

If the element is not there then getElementById method would return null and you are trying to get it's length property, which is throwing the exception. Instead simply check it's defined or not in the if condition.

if (document.getElementById('abcd'))

Use a variable instead of getting element twice. Although there is no val() method for DOM element which is a jQuery method, instead use value property to get value.

var ele = document.getElementById('abcd');

if (ele){
    var abcd = ele.value;
}

This is because there will be not elements in id ="abcd" ,

So try this;

if (document.getElementById('abcd')){
 var abcd = document.getElementById('abcd').val();
}

Try like this.Get value of field then use length to for comparison.

if ($('#abcd').val().length > 0)
{
    var abcd = $('#abcd').val();
}

 if ($('#abcd').val().length > 0) { var abcd = $('#abcd').val(); console.log(abcd); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="abcd" value="hello">

Below code should work..

if (document.getElementById('myElementId') === null){
 alert('Does not exist!');
}else{
 alert('Exist!');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM