JQuery - find the first mat 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(); }); 

change

I need the following line. siblings also get others (e.g. first line)

+7
jquery next siblings
source share
2 answers

Use .nextAll() to get the next siblings of the element and :first to get the first matched element.

Try the following:

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

Demo

+14
source share

You can try using jQuery eq ();

Given a jQuery object representing a set of DOM elements, the .eq () method creates a new jQuery object from a single element inside this set. The supplied pointer determines the position of this element in the set. JQuery documentation

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

In the code, select brother 2ΒΊ with the class "test" in <tr>, which is one of the parents for the clicked <a> (red is the opposite, and you got your code):

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

Check Pen!

0
source share

All Articles