tags:

views:

92

answers:

4
<ul>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
</ul>

How to add some class only for first five <li>?

+3  A: 

$('ul li:lt(5)')

This selects all <li>s of <ul> whose index is less than 5 (i.e., 0-4, or the first five)

Josh Leitzel
i'm no mathematician, but don't you actually mean lt() -- less-than?
larson4
Whoops, fixed. Thanks!
Josh Leitzel
Don't you mean lt(5)? if its less than then its only 0-3. Less than or equal to would include the 5th.
Mark
Ah, you're right. Fixed again.
Josh Leitzel
+8  A: 

Use the :lt selector:

$("ul > li:lt(5)").addClass("foo");
karim79
+3  A: 

Apart from :lt() selector, you can also use slice() function.

$('li').slice(0, 5).addClass('someClass');
BalusC
+1  A: 

for the first five you will want to use

$('ul li:lt(5)').addClass('first-five');

Ross
lt is lower than so lower than 4 is 0 1 2 3 (is first 4 )
Caspar Kleijne
correct you are, edited original
Ross