jquery, find next element by class

JqueryClassElementNext

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

To find the next element with the same class:

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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"});

Solution 5 - Jquery

To find next element by tag name

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryplavozontView Answer on Stackoverflow
Solution 3 - JqueryMorteza ManaviView Answer on Stackoverflow
Solution 4 - JqueryTagFolksView Answer on Stackoverflow
Solution 5 - JquerySergey SorokaView Answer on Stackoverflow