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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:31:16  来源:igfitidea点击:

jQuery - how to check if an element exists?

javascriptjqueryif-statement

提问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

You can use lengthto see if your selector matched anything.

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

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

回答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

You can use the visible selector:

您可以使用可见选择器:

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

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

回答by Hogan

jQuery should be able to find even hidden elements. It also has the :visibleand :hiddenselectors 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.

即使这段代码没有注释,功能也是显而易见的。