jQuery find next element with class

Emil Avramov picture Emil Avramov · Mar 5, 2011 · Viewed 10.7k times · Source

I have a quite simple question, that ate me 4 hours and is not yet solved: How to find next span with specific class with 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 validate it with jQuery. I want if there's an error message, generated with js (just a string), jQuery to find nearest span with class .error and to text() the message in there. I tried with nextAll(), next("span.error") and a lot of other things, but nothing helped me.

Thanks in advance!

Answer

Groovetrain picture Groovetrain · Mar 5, 2011

I know this may not be exactly what you're looking for, but if you've GOT the input, like this:

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

Then you can just do:

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