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?
Use the Array. slice() method to get the first N elements of an array, e.g. const first3 = arr.
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.
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.
Use the :lt
selector:
$("ul > li:lt(5)").addClass("foo");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With