jQuery select all except first
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>
$("div.test:not(:first)").hide();
or:
$("div.test:not(:eq(0))").hide();
or:
$("div.test").not(":eq(0)").hide();
or:
$("div.test:gt(0)").hide();
or: (as per @Jordan Lev's comment):
$("div.test").slice(1).hide();
and so on.
See:
- http://api.jquery.com/first-selector/
- http://api.jquery.com/not-selector/
- http://api.jquery.com/gt-selector/
- https://api.jquery.com/slice/
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.
$("li").not(":first").hide();
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".