17

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)

Jonas
  • 121,568
  • 97
  • 310
  • 388
yossi
  • 3,090
  • 7
  • 45
  • 65

3 Answers3

32

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

Kiran
  • 20,167
  • 11
  • 67
  • 99
0

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!

teefars
  • 612
  • 4
  • 13
  • 1
    Doesn't 100% answer OP's question as 1) OP asked for the next sbilings thus `nextAll` instead of `siblings` (also select those before) and 2) he asked for the next one (first one) thus `eq(0)` instead of `eq(1)`. Although you mentioned it selects the second one, it's still better practice to directly answer the asked question :) – T_D Mar 10 '16 at 16:26
0

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

Gabriel Vasile
  • 2,110
  • 1
  • 14
  • 26