views:

2864

answers:

7

Say I have the following:

<ul>
 <li>First item</li>
 <li>Second item</li>
 <li>Third item</li>
</ul>

How would I select all the child elements after the first one using jQuery? So I can achieve something like:

<ul>
 <li>First item</li>
 <li class="something">Second item</li>
 <li class="something">Third item</li>
</ul>
+5  A: 

http://docs.jquery.com/Traversing/slice

$("li").slice(1).addClass("something");
insin
This is a nice answer, but I feel what I selected as the answer is the more explicit usage. Anyone new to the project will have quicker grasp on what is being done in the selector.
Chris Canal
+15  A: 

You should be able to use the "not" and "first child" selectors.

$("li:not(:first-child)").addClass("something");

http://docs.jquery.com/Selectors/not

http://docs.jquery.com/Selectors/firstChild

twernt
I tried this:$('.certificateList input:checkbox :not(:first-child)')but it didn't work....
Chris Canal
I was being an idiot. Thanks :)
Chris Canal
Will this be slower than the Slice method listed below?
Chris Marasti-Georg
Thanks you very much. this help me too...
GusDe CooL
A: 

This is what I have working so far

$('.certificateList input:checkbox:gt(0)')
Chris Canal
+1  A: 

This should work

$('ul :not(:first-child)').addClass('something');
Pat
+3  A: 

A more elegant query (select all li elements that are preceded by a li element):

$('ul li+li')

Sergey Ilinsky
$("li+li") will likely work faster then $("li:not(:first-child)")
Sergey Ilinsky
A: 

i'd use

$("li:gt(0)").addClass("something");
ignu
+3  A: 

Based on my totally unscientific analysis of the four methods here, it looks like there's not a lot of speed difference among them. I ran each on a page containing a series of unordered lists of varying length and timed them using the Firebug profiler.

$("li").slice(1).addClass("something");

Average Time: 5.322ms

$("li:gt(0)").addClass("something");

Average Time: 5.590ms

$("li:not(:first-child)").addClass("something");

Average Time: 6.084ms

$("ul li+li").addClass("something");

Average Time: 7.831ms

twernt
Thanks for doing this!
Chris Marasti-Georg
I came across this question cause I needed to get all children but the first. I was doing this on all the h3's that were in a div. I ran three of the queries like you had above on my page and came away with :not(:first-child) as being the fastest by 2-3 times. I think the way your page is structured may also play in to profile speeds. Either way though this answer taught me how to use the Firebug profiler and I thank you for that.
RedWolves