admin管理员组文章数量:1201801
I'm using the .length
method in a conditional statement that polls the page for the presence of an externally-loaded object (I can't style it with jQuery until it exists):
function hackyFunction() { if($('#someObject').length<1) { setTimeout(hackyFunction,50) } else { $('#someObject').someMethod() }}
Is length
the best way to do this?
I'm using the .length
method in a conditional statement that polls the page for the presence of an externally-loaded object (I can't style it with jQuery until it exists):
function hackyFunction() { if($('#someObject').length<1) { setTimeout(hackyFunction,50) } else { $('#someObject').someMethod() }}
Is length
the best way to do this?
5 Answers
Reset to default 12If you are simply looking for a specific element you can just use document.getElementById
function hackyFunction() {
if (document.getElementById("someObject")) {
// Exist
} else {
// Doesn't exist
}
}
Yes you should use .length
. You cannot use if ($('#someObject')) ...
because the jQuery selectors return a jQuery object, and any object is truthy in JavaScript.
Yes, .length
is acceptable and is usually what I use.
If you're looking for an ID there should only ever be one of those, so you could also write:
if($('#someObject')[0])
With jQuery, checking length works fine.
if (!$('#someObject').length) {
console.log('someObject not present');
}
Of course with vanilla JavaScript, you can just check with document.getElementById
(if getting elements by id)
if (document.getElementById('someObject')) {
console.log('someObject exists');
}
本文标签: javascriptHow to check for the presence of an elementStack Overflow
版权声明:本文标题:javascript - How to check for the presence of an element? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738601744a2102107.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论