Ahmad
Ahmad

Reputation: 9658

Jquery hide() all elements with certain class except one with certain parent

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.

Upvotes: 1

Views: 889

Answers (2)

charlietfl
charlietfl

Reputation: 171679

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>

Upvotes: 2

AlbertVanHalen
AlbertVanHalen

Reputation: 672

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();

Upvotes: 1

Related Questions