开发者

Make an Indexed Array of <li>'s

开发者 https://www.devze.com 2023-03-16 00:41 出处:网络
I have a typical navigation set开发者_如何学JAVA up in my html, like this: <ul id=\"navigation\">

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');
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消