user2667066 user2667066 - 4 months ago 22
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.


but this does not explicitly
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:


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


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 Source

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

.shown {
  display: none;
<script src=""></script>
<li class="shown">show</li>