Make an Indexed Array of <li>'s
I have a typical navigation set开发者_如何学JAVA up in my html, like this:
<ul id="navigation">
<li>Home</li>
<li>About</li>
<li>Etc</li>
</ul>
I want to create an indexed array of the <li>
's, then .addClass
to any <li>
whose index # is greater than a specified number.
What is the best way to do this?
I apologize for the sparse information, but I'm not really sure how to approach it. Thanks!
$('#navigation > li:gt(42)').addClass('greater-than-the-answer');
Have a look at the selector API docs.
Here you go:
var spec_number = 3;
$('#navigation').children().each(function(index, item){
if(index > spec_number) $(item).addClass('indexGreat');
})
Supposing you want to add the class to items with index > 42, you can filter
the collection and add the class to all items that pass from the filter:
$("#navigation li")
.filter(function(index) { return index > 42; })
.addClass("myClass");
$('#navigation li').each(function(){
if($(this).index() > 2)
{
$(this).addClass('whatever');
}
});
精彩评论