Question

How can i get the first (next) element in the list that matches the selector ?

Example:

<table>
  <tr class="test"><td>not this one</td></tr>
  <tr><td><a title="test">click</a></td></tr>
  <tr><td>not this one</td></tr>
  <tr class="test"><td>this one</td></tr>
  <tr class="test"><td>ignore this as well</td></tr>
</table>

$("a").on('click', function(eve){
  $(this).parents("tr").???(".test").toggle();
});

edit

I need the following row. siblings gets others as well (like the first row)

Was it helpful?

Solution

Use .nextAll() to get following siblings of an element and :first to get first matched element.

Try this:

$("a").on('click', function(eve){
  $(this).parents("tr").nextAll(".test:first").toggle();
});

DEMO

OTHER TIPS

You may try using jQuery eq();

Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set. Documentation on jQuery

<table>
  <tr class="test"><td>not this one</td></tr>
  <tr><td><a title="test">click</a></td></tr>
  <tr><td>not this one</td></tr>
  <tr class="test"><td>this one</td></tr>
  <tr class="test"><td>ignore this as well</td></tr>
</table>

The code would select the 2º sibling with the class "test" of the < tr > that is one of the parents to the clicked < a > (red this reversely and you got your code):

$("a").on('click', function(){
  $(this).parents("tr").siblings(".test").eq(1).toggle();
});

Check the Pen!

You can use the .next() selector:

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.

For your case, use

$(this).parents("tr").next().next()

or

$(this).closest("tr").next().next()

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