admin管理员组

文章数量:1279019

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 ?

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 ?

Share Improve this question asked Feb 9, 2017 at 4:44 Upendra SharmaUpendra Sharma 6853 gold badges12 silver badges29 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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 parison.

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./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!');
}

本文标签: quotUncaught TypeError Cannot read property 39length39 of null JAVASCRIPTStack Overflow