如果孩子为空则隐藏父范围

时间:2019-10-31 06:52:30

标签: jquery

如果子跨度为空,我想隐藏整个跨度。

我有以下HTML结构:

<span class="training-crew-wrapper">
    <h5>Title 1</h5>
    <span class="training-vessels-wrapper">
        Content 1
        Content 1
        Content 1
    </span>
</span>

<span class="training-crew-wrapper">
    <h5>Title 2</h5>
    <span class="training-vessels-wrapper">

    </span>
</span>

<span class="training-crew-wrapper">
    <h5>Title 3</h5>
    <span class="training-vessels-wrapper">
        Content 3
        Content 3
        Content 3
    </span>
</span>

在空training-vessels-wrapper实例中,我想隐藏其父training-crew-wrapper。我有以下JQuery:

$('.training-crew-wrapper').each(function() {

    $length = $(this).find( ".training-vessels-wrapper" ).text().replace(/\s/g,'').length;

    if ( $length == 0 ) {
        $( ".training-crew-wrapper" ).empty();
    }

});

不幸的是,我的JQuery似乎只是清空training-crew-wrapper的所有实例。我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

我希望您正在尝试这样做

$('.training-crew-wrapper').each(function() {
      var htmlstring = $(this).find( ".training-vessels-wrapper" ).html();
      htmlstring = (htmlstring.trim) ? htmlstring.trim() : htmlstring.replace(/^\s+/,''); 
      if(htmlstring == ''){
        $(this).find( ".training-vessels-wrapper" ).parent().remove();
      } 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="training-crew-wrapper">
    <h5>Title 1</h5>
    <span class="training-vessels-wrapper">
        Content 1
        Content 1
        Content 1
    </span>
</span>

<span class="training-crew-wrapper">
    <h5>Title 2</h5>
    <span class="training-vessels-wrapper"> 
    </span>
</span>

<span class="training-crew-wrapper">
    <h5>Title 3</h5>
    <span class="training-vessels-wrapper">
        Content 3
        Content 3
        Content 3
    </span>
</span>

My CodePen Example