Search code examples
jqueryjquery-selectorssiblings

JQuery - find first sibling matches selector


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)


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