Reputation: 3126
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
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
Reputation: 76547
Solution:
The following will add 'fred'
to all <li>
elements after the third:
$('ul.my_class li:gt(2)').addClass('fred');
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.
Upvotes: 2
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
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