BenM
BenM

Reputation: 53198

Loop over elements until match found in jQuery

I have a series of li items and need the most effective way to loop over them and return the index. I need to cross-check the li's class though, and not return the index if it has a certain class.

This is basically for an application-style menu with keyboard support. Essentially, consider the following markup:

<ul>
    <li class="selected">First Item</li>
    <li class="disabled">Second Item</li>
    <li class="separator">Third Item</li>
    <li>Fourth Item</li>
</ul>

I want a function that I can use to loop through the li elements, and return the next index (the class of selected will be applied to the next selectable item). At the moment, I am looping over and simply checking if the li has a class of separator, if it does, increment the index and return it.

However, in the above example, the function should return 3, because any item with a class of disabled or separator cannot be selected.

Could anyone offer some advice on how I might achieve this using jQuery? I was thinking that it might be possible to do something like this:

function get_next_index()
{
    var current_index = $('ul li.selected');
    var index = $('ul li:gt(' + current_index + ')').not('.disabled').not('.separator').get(0).index();
    if(!index || index < current_index)
    {
        return -1;
    }
    else
    {
        return index;
    }
}

Upvotes: 0

Views: 1465

Answers (3)

Interrobang
Interrobang

Reputation: 17434

My contribution:

$("li.selected").nextAll(":not(.disabled,.separator)").first().index();

This takes all following siblings, filters out the .disabled and the .separator, and returns the index of the first one.

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85046

Something like this should work:

alert($("li:not(.disabled,.separator)").index());

You can see it in action here:

http://jsfiddle.net/Zf9Vv/

I was a little confused on your question so please let me know if i got anything wrong. I would recommend reading up on the index method to see if that does what you expect.

Upvotes: 3

Jake Feasel
Jake Feasel

Reputation: 16955

$('li').each(function () {

  if (! $(this).hasClass('disabled'))
  {
    // code for non-disabled li goes here
  }

});

I think this is basically what you're asking for. Not sure what you mean by "return the index" - do you just want an array of indexes for all the items that are without the "disabled" class?

Upvotes: 0

Related Questions