jQuery 使用jQuery检查父元素是否包含某些子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9833853/
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-27 11:22:05  来源:igfitidea点击:

Check if parent element contains certain child element using jQuery

jqueryhtml

提问by UserIsCorrupt

<div id="example">
  <div id="test"></div>
</div>

<div id="another">Blah</div>

I want to set $('#another').hide()but only if #examplecontains a child element called#test, is this possible? It seems like it would be.

我想设置$('#another').hide()但仅当#example包含一个名为 的子元素时#test,这可能吗?好像会的。

回答by elclanrs

Use length

length

if ($('#example').find('#test').length) {
    // found!
}

回答by Mike Geise

I think what you are looking for is the following

我认为您正在寻找的是以下内容

if (jQuery.contains($('#example'), $('#test')) {
    $('#another').hide();
}

This might work as well, not sure off the top of my head.

这可能也有效,不确定我的头顶。

if ($('#test', $('#example')).size() > 0) {
    $('#another').hide();
}

回答by Brian Warfield

<script>
    var test = $('#example #test').length();
    if(test !== 0){
        $('#another').hide();
    }
</script>

回答by Alex Lomakin

jQuery manual suggests to use:

jQuery 手册建议使用:

if ($('#parent').has('#child').length) {
    //do something
}

http://api.jquery.com/has/

http://api.jquery.com/has/

回答by fengd

it's pretty simple.

这很简单。

$(document).ready(function(){
    if($('#example').children('#test').length > 0)
    {
        $('#another').hide();
    }
});?

http://jsfiddle.net/8rrTp/

http://jsfiddle.net/8rrTp/