Cleanest way to get the next sibling in jQuery

To elaborate on the comments above:

You cannot write:

  • next("a"), because next() only tries to match the very next element. It will hit the <br> element and match nothing.

  • closest("a") , because closest() walks up the ancestor chain, starting with the element itself, and therefore will miss the <a> elements.

You can write:

  • next().next(), as Arend suggests. That’s probably the fastest solution, but it makes the <br> elements mandatory.

  • nextAll("a"), but that can return multiple elements (and will do so with your markup sample). Chaining into first() would prevent it, but nextAll() still would have to iterate over all the next siblings, which can make it slow depending on the complexity of the markup inside your <div> elements.

  • nextUntil("a").last().next(), which only iterates over the next siblings until it finds a link, then returns the immediate next sibling of the last element matched. It might be faster than nextAll(), again, depending on your markup.

Leave a Comment