Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery, find next element by class

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?

like image 384
Alex Avatar asked Sep 08 '10 17:09

Alex


People also ask

How to find next element in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

How to get nextsibling in jQuery?

next( [selector ] )Returns: jQuery. Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

What is closest tr in jQuery?

The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.

What does jQuery find return?

jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.


2 Answers

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'); 
like image 83
Nick Craver Avatar answered Sep 22 '22 14:09

Nick Craver


To find the next element with the same class:

$(".class").eq( $(".class").index( $(element) ) + 1 ) 
like image 37
plavozont Avatar answered Sep 20 '22 14:09

plavozont