Dom
Dom

Reputation: 3126

Adding class to each item after third with jQuery

I have a very simple HTML which is as follow:

<ul class="my_class">
<li>List</li>
<li>List</li>
<li>List</li>
<li>List</li>
<li>List</li>
</ul>

What I am trying to acheave is to add a class "fred" to every single <li> that is appending after 3rd <li>.

This small function is adding it to hhe first 3 items :

$('ul.my_class li:lt(3)').addClass('fred');

Thank you all for your help in advance!

Dom

Upvotes: 1

Views: 240

Answers (5)

Marat Tanalin
Marat Tanalin

Reputation: 14123

Use the following selector: UL.my_class > LI + LI + LI + LI

:gt() selector is nonstandard and therefore is much slower in browsers with native querySelectorAll() support (all current browsers have this support). :gt() selector page on api.jquery.com has note about that.

:nth-child() is not supported by IE8 that have support for querySelectorAll() and therefore :nth-child() in IE8 is potentially slower too.

Upvotes: -1

Schiavini
Schiavini

Reputation: 2939

This will do:

$('ul.my_class li:gt(2)').addClass('fred');

Upvotes: 5

Rion Williams
Rion Williams

Reputation: 76547

Solution:

The following will add 'fred' to all <li> elements after the third:

$('ul.my_class li:gt(2)').addClass('fred');​

Working Solution Example

Explanation of your existing code:

$('ul.my_class li:lt(3)').addClass('fred');​

will add 'fred' to all <li> elements from the first to the third.

Example of your existing code

Upvotes: 2

soniiic
soniiic

Reputation: 2685

You can use the following script:

$('ul.my_class li:nth-child(1n+4)').addClass('fred');

You can test the result here: http://css-tricks.com/examples/nth-child-tester/

Update: Even after getting a few upvotes, I do prefer Schiavini's answer. It's more readable and more semantically correct

Upvotes: 6

Tilt
Tilt

Reputation: 677

Use gt (greater than) instead of lt (less than), and start from 2 because the index is zero-based:

$('ul.my_class li:gt(2)').addClass('fred');

Here are the official specs: :gt() Selector – jQuery API

Upvotes: 0

Related Questions