Upendra Sharma
Upendra Sharma

Reputation: 685

"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 ?

Upvotes: 2

Views: 32388

Answers (4)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

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

So try this;

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

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

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;
}

Upvotes: 4

Dillip
Dillip

Reputation: 38

Below code should work..

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

Upvotes: 0

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

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">

Upvotes: 0

Related Questions