jquery, find next element by class

Alex picture Alex · Sep 8, 2010 · Viewed 236.4k times · Source

How can i find the next element by class.

i tried with $(obj).next('.class'); but this returns classes only in $(obj) parent. I need to take the next element anywhere throughout the code by class name. Because my code looks like

<table>
<tr><td><div class="class">First</div></td></tr>
<tr><td><div class="class">Second</div></td></tr>
</table>

Is this possible?

Answer

Nick Craver picture Nick Craver · Sep 9, 2010

In this case you need to go up to the <tr> then use .next(), like this:

$(obj).closest('tr').next().find('.class');

Or if there may be rows in-between without the .class inside, you can use .nextAll(), like this:

$(obj).closest('tr').nextAll(':has(.class):first').find('.class');