I have a small jQuery selectors question, I have the following html:
<
@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.
$(".member-info").not(".first").hide(); // Class selector
or
$(".member-info").not(":first").hide(); // Positional selector
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 than slice(1)
, but is very readable as "I want all except the first one".
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:
$('.member-info:not(:first)');//grab all .member-info except the first match