JQuery find next element with class

I have a pretty simple question that ate me 4 hours and haven't decided yet: how to find the next span with a specific class using jQuery? I have the following html

<tr> <td align="right">:&nbsp;</td> <td align="left"> <input type="text" value="<?=$profileSQL['user_name']; ?>" name="user_name" class="input required" /> </td> </tr> <tr> <td align="right" colspan="2"> <span class="error"></span> </td> </tr> 

and I check it with jQuery. I want, if there is an error message generated using js (string only), jQuery to find the closest span with .error and text() there. I tried with nextAll() , next("span.error") and more, but nothing helped me.

Thanks in advance!

+4
source share
4 answers

I know that this may not be exactly what you are looking for, but if you have an input, for example:

 var input = $('input[name="user_name"]'); 

Then you can simply do:

 input.parents('tr').eq(0).next().find('.error').text(nameErrEmptyMsg); 
+1
source

the problem is that .next () and .nextAll () only search through siblings (elements that have the same parent element).

From the jQuery documentation:

Description: Get all of the following siblings of each element in the set of matched elements, optionally filtered by the selector.

In your case, you have:

  <tr> <td> title here</td> <td><input name="user_name"/> </td> </tr> <tr> <td colspan="2"> <span class="error"></span> </td> </tr> 

As I understand it, your jQuery code is running on input, right? In this case, before calling newxt () or nextAll (), you must first go to 2 levels until and then select the next one, because there is something you want to find, therefore:

here is a working example to check it out: http://jsfiddle.net/EM5Gw/

+2
source

try

  console.log($("td>span").next().find(".error").text()) 
0
source

You can use next('span.error') :

http://jsfiddle.net/wPZgg/

0
source

Source: https://habr.com/ru/post/1342421/


All Articles