how to select list-items having index value within a certain range?
I want to assign a class to the list-items of an ul li
list having 开发者_如何学C.index()
value between 10 to 20.
How do I select those elements using jQuery?
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
...
...
...
...
li>Thirty</li>
</ul>
So I want something like
$('#id').click(function(){
//Assign class 'classname' to those li elements
//between 10th and 20th (index numbers) in the list
if([li element's index is between 10 and 20]).addClass('classname');
});
Use slice
to get a subset of the elements in a selection:
$('li').slice(10, 20).addClass('classname');
Although I recommend using lonesomeday's method, here is one way to do it purely with selectors:
$("ul li:gt(8) + li:lt(10)").addClass('classname');
Note that as gt
and lt
use 0 based index, if you want >= 10
you need to use 8 (which is greater than 9).
example: http://jsfiddle.net/GybxF/21/
Altough lonesomeday's answer is correct and probably better. Here is a different solution.
http://jsfiddle.net/E4U6Y/
HTH :)
精彩评论