[英]How to check for the presence of an element?
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): 我在一个条件语句中使用
.length
方法,该语句轮询页面是否存在外部加载的对象(我不能使用jQuery对其进行样式化,直到它存在):
function hackyFunction() { if($('#someObject').length<1) { setTimeout(hackyFunction,50) } else { $('#someObject').someMethod() }}
Is length
the best way to do this? length
是最好的方法吗?
If you are simply looking for a specific element you can just use document.getElementById
如果您只是在寻找特定元素,则可以使用
document.getElementById
function hackyFunction() {
if (document.getElementById("someObject")) {
// Exist
} else {
// Doesn't exist
}
}
Yes you should use .length
. 是的你应该使用
.length
。 You cannot use if ($('#someObject')) ...
because the jQuery selectors return a jQuery object, and any object is truthy in JavaScript. 你不能使用
if ($('#someObject')) ...
因为jQuery选择器返回一个jQuery对象,并且任何对象在JavaScript中都是真实的。
如果你正在寻找一个ID,那么它应该只有一个,所以你也可以这样写:
if($('#someObject')[0])
是的, .length
是可以接受的,通常是我使用的。
With jQuery, checking length works fine. 使用jQuery,检查长度可以正常工作。
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) 当然使用vanilla JavaScript,您只需检查
document.getElementById
(如果按id获取元素)
if (document.getElementById('someObject')) {
console.log('someObject exists');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.