oursgris
oursgris

Reputation: 2882

Find previous div of a specific class with Jquery

I use jquery and I want to find the previous div which has the "error" class

My html code :

<table class="questions">
    <tr>
        <td class="heading">1
            <div class="error"></div>
        </td>

        <td colspan="4">
            <textarea class="textcontrol required" name='questionT136'>
            </textarea>
        </td>
    </tr>

    <tr>
        <td></td>

        <th><label for="reponse137-3">Très satisfaisant</label></th>
        <th><label for="reponse137-4">Satisfaisant</label></th>
        <th><label for="reponse137-5">Insatisfaisant</label></th>
    </tr>

    <tr class="q">
        <td class="heading">
            2
            <div class="error"></div>
        </td>

        <td class="questionradio"><input class="required" id='reponse137-3'
        name='questionN137' type='radio' value='3'></td>

        <td class="questionradio"><input class="required" id='reponse137-4'
        name='questionN137' type='radio' value='4'></td>
    </tr>
</table>

For example, from reponse137-3, I'd like to change the value the previous class="error". I allready tryied to access to that object with :

$('#reponse137-3').prev(".error")

but it doesn't work. I think because it hasn't the same parent, so I tryied :

$('#reponse137-3').prev("tr").next(".error")

How can I do ?

Upvotes: 0

Views: 4874

Answers (2)

Alberto Le&#243;n
Alberto Le&#243;n

Reputation: 2921

You need to go up three times to arrive to table, and later find error

$('#reponse137-3').parent().parent().parent().find('.error');

First parent go to th, second to tr and thirth to table, then find within table what element has class named .error And you will get it

Upvotes: 2

Blazemonger
Blazemonger

Reputation: 92983

Assuming your .error div is always in the same table row:

$('#reponse137-3').closest('tr').find('.error:first');

http://jsfiddle.net/vkfF8/

Upvotes: 4

Related Questions