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

Use*_*upt 33 html jquery

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

<div id="another">Blah</div>
Run Code Online (Sandbox Code Playgroud)

我想设置,$('#another').hide()但只有#example包含一个被调用的子元素#test,这可能吗?好像是这样.

elc*_*nrs 68

使用 length

if ($('#example').find('#test').length) {
    // found!
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*ise 7

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

if (jQuery.contains($('#example'), $('#test')) {
    $('#another').hide();
}
Run Code Online (Sandbox Code Playgroud)

这可能也有效,但不能确定.

if ($('#test', $('#example')).size() > 0) {
    $('#another').hide();
}
Run Code Online (Sandbox Code Playgroud)

  • 应该使用DOM元素作为参数调用'contains'而不是jQuery对象吗?http://api.jquery.com/jQuery.contains/ (4认同)

Ale*_*kin 5

jQuery 手册建议使用:

if ($('#parent').has('#child').length) {
    //do something
}
Run Code Online (Sandbox Code Playgroud)

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