简体   繁体   English

检查子元素,如果子元素存在则隐藏父元素

[英]check for child element, hide parent if child exists

I have tried this: 我已经试过了:

<script>
$(document).ready(function() {
  $('#title_article:not(:has(>hr:first-child))').hide();
});
</script>

But never shows.. 但是从不显示..


<div id="title_article">
    <span style="padding-left:121px;">Article | </span>
    <span class="entry-date"><?php echo get_the_date(); ?></span>
</div>

Seeking to check for child element of <hr> if <hr> exists hide parent or #title_article 试图检查<hr>子元素是否存在<hr>隐藏父级或#title_article

<hr> would not be within <div id="title_article"></div> but below: <hr>不在<div id="title_article"></div>但在以下范围内:

<!-- page content -->

    <div id="title_article></div>
    <hr>

<!-- page content -->
$(document).ready(function() { 

 if($("#title_article").next("hr").length==0)

    $("#title_article").hide()

});

http://fiddle.jshell.net/prollygeek/57gcx6or/3/ http://fiddle.jshell.net/prollygeek/57gcx6or/3/

Edit: Use .siblings() 编辑:使用.siblings()

You are looking for .next() 您正在寻找.next()

Get the immediately following sibling of each element in the set of matched elements. 获取匹配的元素集中每个元素的紧随其后的同级。 If a selector is provided, it retrieves the next sibling only if it matches that selector. 如果提供了选择器,则仅当与该选择器匹配时才检索下一个同级。

You have to do something like: 您必须执行以下操作:

if ($('#title_article').next('hr').length)
    $('#title_article').hide();

In your example, <hr> is not a child element of #title_article , but a sibling. 在您的示例中, <hr>不是#title_article的子元素,而是同级元素。

You could use the children function jQuery has to offer. 您可以使用jQuery必须提供的功能。

Try it in this context: 在这种情况下尝试:

if($('#title_article').children('hr').length > 0) {
    $('#title_article').hide();
 }

Or this: 或这个:

if($('#title_article').children('hr').length != 0) {
    $('#title_article').hide();
 }

You could also use the parent function 您还可以使用函数

Try it in this context: 在这种情况下尝试:

$('#title_article hr').parent().hide();

This will hide every #title_article that has an hr in it. 这将隐藏其中所有#title_article hr #title_article

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM