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 badges4 Answers
Reset to default 4If 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
版权声明:本文标题:"Uncaught TypeError: Cannot read property 'length' of null JAVASCRIPT - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741211080a2359133.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论