views:

160

answers:

2

I have the following list

<ul>
  <li id="item1">Item 1</li>
  <li id="item2">Item 2</li>
  <li>Item 3</li>
  <li id="item4">Item 4</li>
</ul>

Using jQuery, I'm trying to traverse the list of LIs whose IDs start with "item".

var nextItemWithItemID = $("#item2").next("li[id^='item']);

However, when I run this code, I end up retrieving "Item 3" rather than "Item 4".

How can I get jQuery to get the proper next item from a filtered list of LIs?

+5  A: 

You want to use nextAll(). Next is only going to retrieve the sibling immediately following the current element. NextAll() will consider all of the following siblings.

var nextItemWithItemID = $('#item2').nextAll('li[id^=item]:first');
tvanfosson
@tvanfosson Can't believe I've never come across this issue before, was actually surprised with .next() didn't work as expected...I could swear it used to go to the next matching sibling, oh well. +1 This i the correct approach.
Nick Craver
@Nick Craver --it almost is. This will get you all of them, but doesn't get the OP to the next item quite yet. I'm sure all you have to do is index it, right? .index(0) ? Not sure. Might want to be explicit with that.
D_N
@DN - fooled by the example. It should probably have a `:first` filter, too. Will update.
tvanfosson
@tvanfosson - That did the trick! Thanks everyone.
goombaloon
+1  A: 

I was having this problem last night. While @tvanfosson provides a way to get to all of the succeeding siblings, if you want the next item that matches that criteria, I came up with the following solution (adapted to your example):

var nextItemWithItemID = $("#item2").nextUntil("li[id^='item']").andSelf().next();

That's it. Using nextUntil() grabs everything until the term, but not including it, so you have to use next(). But if the returned set is empty (if there's nothing between your initial selector and the next thing that matches your query), that won't work--andSelf() solves that.

D_N