user2667066 user2667066 - 17 days ago 7
jQuery Question

Hide all but one match, which is shown, in one jquery line

There seem to be many answers on SO to hide all but one element of a selector, e.g.

$('li').not('.shown').hide()


but this does not explicitly
show()
the element
<li class="shown">
if it has been hidden previously. To deal with this, other SO answers suggest a 2 liner, which has the disadvantage of hiding all the elements first, then showing one, which may cause flicker:

$('li').hide()
$('li.shown').show()


Is there a jQuery syntax which I can use which does this in a single loop? I'm not sure whether e.g.

$('li').hide().filter('.shown').show()


will do this, or whether that simply does the same as the 2 liner, looping first over all the matches, then later switching one back on again.

Answer

You can chain the two by using $.not('.shown') or :not(.shown) when you hide the li's, then use $.end() and use $.filter('.shown').show()

$('li').not('.shown').hide().end().filter('.shown').show();
.shown {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>asdf</li>
<li>foo</li>
<li class="shown">show</li>
<li>bar</li>