0

I have a typical navigation set 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!

4 Answers 4

6
$('#navigation > li:gt(42)').addClass('greater-than-the-answer');

Have a look at the selector API docs.

Sign up to request clarification or add additional context in comments.

3 Comments

I did not know there was a selector for that. Didn't know it would be that simple! Thanks Matt.
@Rrryyyaaannn there's a selector for everything, just memorize the API
I see what you mean. Thanks again.
1

Here you go:

var spec_number = 3;
$('#navigation').children().each(function(index, item){
    if(index > spec_number) $(item).addClass('indexGreat');
})

2 Comments

... or use the existing selector syntax.
@Tomalak -- that is true as well. i had a bit of a brain freeze when answering the question
0

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");

1 Comment

... or use the existing selector syntax.
0
$('#navigation li').each(function(){
    if($(this).index() > 2)
    {
        $(this).addClass('whatever');
    }
});

1 Comment

... or use the existing selector syntax.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.