jQuery next() with selector is not finding specified element based on class

I have an HTML structure that looks like:

<a id="checkAllButton" onclick="...">...
<a id="uncheckAllButton" onclick="...">...
<span ...>
<div class="box collapsible-box csvTable-box">...

And I have a jQuery reference to the <a> as a result of the onClick of the checkAllButton:

When I examine (as a watch variable):

$(this).next().next().next()

I see:

0: div.box.collapsible-box.csvTable-box

However, when I use:

$(this).next('.csvTable-box')

It comes back with an empty object. It seems it should be pulling in that <div>, but I can’t seem to determine why it’s skipping over it.

Chrome Watch Expressions


solution

It’s because the .next() method only returns the next adjacent element. If the very next sibling element doesn’t have class .csvTable-box, nothing is selected.

If you want to iterate through all the next sibling elements, use the .nextAll() method, and then chain .first() if you want to reduce the set so that only the first match is returned.

$(this).nextAll('.csvTable-box').first();