Javascript jQuery - 如何检查元素是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5293041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - how to check if an element exists?
提问by A-OK
I know that you can test for width()
or height()
but what if the element's display property is set to none? What other value is there to check to make sure the element exists?
我知道您可以测试width()
或者height()
但是如果元素的 display 属性设置为 none 呢?还有什么其他值需要检查以确保元素存在?
回答by Bjarki Heiear
回答by Hussein
Assuming you are trying to find if a div exists
假设您正在尝试查找 div 是否存在
$('div').length ? alert('div found') : alert('Div not found')
Check working example at http://jsfiddle.net/Qr86J/1/
在http://jsfiddle.net/Qr86J/1/检查工作示例
回答by developer2001
if ($("#MyId").length) { ... write some code here ...}
This from will automatically check for the presence of the element and will return true if an element exists.
这 from 将自动检查元素是否存在,如果元素存在,则返回 true。
回答by Steve Wellens
回答by Hogan
jQuery should be able to find even hidden elements. It also has the :visible
and :hidden
selectors to find both visible and hidden elements.
jQuery 甚至应该能够找到隐藏的元素。它还有用于查找可见和隐藏元素的:visible
和:hidden
选择器。
Does this help? Not sure without more info.
这有帮助吗?不确定没有更多信息。
回答by V. Kovpak
I use this:
我用这个:
if ($('.div1').size() || $('.div2').size()) {
console.log('ok');
}
回答by Imagerie Numérique
Mostly, I prefer to use this syntax :
大多数情况下,我更喜欢使用这种语法:
if ($('#MyId')!= null) {
// dostuff
}
Even if this code is not commented, the functionality is obvious.
即使这段代码没有注释,功能也是显而易见的。