James
James

Reputation: 43647

How to get the first X elements?

I have a list with a bunch of elements:

<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 can I target the first five li elements and add a class to them?

Upvotes: 24

Views: 20226

Answers (5)

Myst
Myst

Reputation: 1

If you're using $.each method, and you want to use a limit condition into it, i would suggest the following:

var $elems = $('ul li');

$.each($elems, function(i){
   var $this = $(this);

   if (i < n) {
      $this.addClass('someClass');
   } else {
      $this.addClass('anotherClass');
   }
});

Upvotes: 0

Ross
Ross

Reputation: 17967

for the first five you will want to use

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

Upvotes: 2

BalusC
BalusC

Reputation: 1108712

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

$('li').slice(0, 5).addClass('someClass');

Upvotes: 26

karim79
karim79

Reputation: 342635

Use the :lt selector:

$("ul > li:lt(5)").addClass("foo");

Upvotes: 56

Josh Leitzel
Josh Leitzel

Reputation: 15199

$('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)

Upvotes: 6

Related Questions