122

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?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Alex
  • 1,571
  • 3
  • 13
  • 16

5 Answers5

179

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');
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • It would be easier to do this: $(obj).closest('tr').nextAll('.class')[0]; – StuR Jul 16 '12 at 13:55
  • 3
    @StuR - that wouldn't work here, since .nextAll() only looks at sibling elements. You need something that looks at descendants to find the next
    the question wants.
    – Nick Craver Jul 17 '12 at 01:29
  • 1
    And what if wanted to get an attribute from that HTMLObject returned? Like an `$(obj).closest('tr').nextAll('.class')[0].attr('data-attribute');` – Dennis Braga Sep 02 '14 at 16:37
  • 1
    You may also need to use: **.parent().next("")** if the element has no siblings – shasi kanth Jun 04 '18 at 11:37
29

To find the next element with the same class:

$(".class").eq( $(".class").index( $(element) ) + 1 )
plavozont
  • 807
  • 9
  • 17
20

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')
Morteza Manavi
  • 33,026
  • 6
  • 100
  • 83
0

Given a first selector: SelectorA, you can find the next match of SelectorB as below:

Example with mouseover to change border-with:

$("SelectorA").on("mouseover", function() {
    var i = $(this).find("SelectorB")[0];
    $(i).css({"border" : "1px"});
    });
}

General use example to change border-with:

var i = $("SelectorA").find("SelectorB")[0];
$(i).css({"border" : "1px"});
TagFolks
  • 244
  • 3
  • 5
0

To find next element by tag name

  function findNext(start, tag)
    {
      while(start.nodeName !== tag)
      {
            start = start.nextElementSibling;
      }
      return start;
    }