Question

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?

Was it helpful?

Solution

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');

OTHER TIPS

To find the next element with the same class:

$(".class").eq( $(".class").index( $(element) ) + 1 )

You cannot use next() in this scenario, if you look at the documentation it says:
Next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling that matches the selector.

so if the second DIV was in the same TD then you could code:


// Won't work in your case
$(obj).next().filter('.class');

But since it's not, I don't see a point to use next(). You can instead code:

$(obj).parents('table').find('.class')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top