JQuery - find first sibling matches selector
Asked Answered
A

3

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)

Amphora answered 14/5, 2014 at 16:57 Comment(2)
what are you trying to do??Schiro
i have some dynamic rows that are toggled on and off by the prev' row. i can't use 'next()' since i can't tell which of the rows i will have - and how many.Amphora
A
33

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

Aldenalder answered 14/5, 2014 at 16:58 Comment(0)
B
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!

Bulletin answered 25/8, 2015 at 17:3 Comment(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 :)Anacoluthia
V
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()

Vallo answered 21/7, 2021 at 7:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.