In jQuery how do I use a selector to access all but the first of an element? So in the following code only the second and third element would be accessed. I know I can access them manually but there could be any number of elements so thats not possible. Thanks.
<div class='test'></div>
<div class='test'></div>
<div class='test'></div>
Because of the way jQuery selectors are evaluated right-to-left, the quite readable
li:not(:first)
is slowed down by that evaluation.An equally fast and easy to read solution is using the function version
.not(":first")
:e.g.
JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6
This is only few percentage points slower than
slice(1)
, but is very readable as "I want all except the first one".My answer is focused to a extended case derived from the one exposed at top.
Suppose you have group of elements from which you want to hide the child elements except first. As an example:
We want to hide all
.child
elements on every group. So this will not help because will hide all.child
elements exceptvisible#1
:The solution (in this extended case) will be:
or:
or:
or:
or: (as per @Jordan Lev's comment):
and so on.
See: