1

My question is similar to this one: Jquery hide() all elements with certain class except one. However in my case I have a certain parent.

I tried:

$('.slideNum').hide();
$('#marginRight ul li.selBar.slideNum').show();

The slideNum that has selBar as parent shouldn't be hidden, but it does!

Unlike the popular answer I didn't use "not" because the condition is for the parent and not for the element itself.

Ahmad
  • 8,811
  • 11
  • 76
  • 141

2 Answers2

2

You can use not() by using the parent as part of selector to filter out

$('.slideNum').not('.selBar *').hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="slideNum">Should be hidden</div>
<div class="selBar">
  <div class="slideNum">Should be visible</div>
</div>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

You can use a function in the not filter (https://api.jquery.com/not/) like this:

   $('.slideNum').not(function () {
        return $(this).parent(".selBar").length !== 0;
    }).hide();
Ahmad
  • 8,811
  • 11
  • 76
  • 141
AlbertVanHalen
  • 632
  • 4
  • 12