Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first X elements?

Tags:

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?

like image 317
James Avatar asked Sep 10 '10 15:09

James


People also ask

How do I find the first element of an array?

Use the Array. slice() method to get the first N elements of an array, e.g. const first3 = arr.

How do you find the first n number of an element from an object?

The catch here is that you can use the Object. keys(...)[ index] API to retrieve the element's key based on their position. Then all you need to do is just loop n number of times and using the derived key push it into another object.

How do you take two elements of an array?

To get the first 2 elements of an array, call the slice method passing it a start index of 0 and an end index of 2 as parameters. The slice method will return a new array containing the first 2 elements of the original array. Copied! We used the Array.


1 Answers

Use the :lt selector:

$("ul > li:lt(5)").addClass("foo"); 
like image 114
karim79 Avatar answered Oct 02 '22 14:10

karim79