2

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 ?

4 Answers 4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

So try this;

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

Comments

0

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

Comments

0

Below code should work..

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.