I have a small jQuery selectors question, I have the following html:
<div class="member-info first"></div>
<div class="member-info"></div>
<div class="member-info"></div>
I want to hide (using jQuery) all the divs that holds the "member-info" class, but not the one holding the "first" class, any thoughts?
All possible ways that come to my mind. I also made JavaScript performance comparison where you can find some unexpectable results.
All of this samples work with v1.10.* of jQuery.
Most times this one is the fastest
$(".member-info").slice(1).hide();
and looks like relevant, not brainstormed answerhow about
$('.member-info').not('.first').hide();
I came across this issue as well. However, I did not conveniently have a class named
first
marking my element for exclusion. Here was the solution I used for the selector in the context of this example:Use the :not() selector. For example:
If first is really always the first child, try
@AuthorProxy
,@David Thomas
and@Maximilian Ehlers
all suggest$('.member-info').not('.first').hide();
in their answers which is a very fast, and very readable solution.Because of the way jQuery selectors are evaluated right-to-left, the quite readable
".member-info:not(.first)"
is actually slowed down by that evaluation.A fast and easy to read solution is indeed using the function version
.not(".first")
or even just.not(":first")
:e.g.
or
JSPerf of related selectors: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6
.not(':first')
is only few percentage points slower thanslice(1)
, but is very readable as "I want all except the first one".This doesn't quite answer your question, but you could skip the first matched element using gt.
For example:
See: http://api.jquery.com/gt-selector/