jQuery - 如何检查元素是否存在?

时间:2011-03-13 22:54:06

标签: javascript jquery if-statement

我知道您可以测试width()height()但是如果元素的display属性设置为none会怎么样?还有哪些其他值可以检查以确保元素存在?

7 个答案:

答案 0 :(得分:148)

您可以使用length查看您的选择器是否匹配任何内容。

if ($('#MyId').length) {
    // do your stuff
}

答案 1 :(得分:15)

假设您正在尝试查找div是否存在

$('div').length ? alert('div found') : alert('Div not found')

检查http://jsfiddle.net/Qr86J/1/

处的工作示例

答案 2 :(得分:2)

您可以使用可见选择器:

http://api.jquery.com/visible-selector/

答案 3 :(得分:2)

jQuery应该能够找到甚至隐藏的元素。它还有:visible:hidden选择器来查找可见元素和隐藏元素。

这有帮助吗?不确定没有更多信息。

答案 4 :(得分:2)

if ($("#MyId").length) { ... write some code here ...}

此from将自动检查元素是否存在,如果元素存在,则返回true。

答案 5 :(得分:0)

我用这个:

if ($('.div1').size() || $('.div2').size()) {
    console.log('ok');
}

答案 6 :(得分:-3)

大多数情况下,我更喜欢使用这种语法:

if ($('#MyId')!= null) {
    // dostuff
}

即使没有评论此代码,功能也很明显。