Clément Andraud
Clément Andraud

Reputation: 9269

Retrieve specific element before an other in jQuery

I have a html like that :

<fieldset>
<legend>Sondage</legend>
<input type="hidden" value="formulaire_test/poll1352736068616/testencode" name="pollpost">
<p class="question">Q1</p>
<p class="response">
<input id="R010101" type="radio" value="A" name="R0101">
<label for="R010101">R11</label>
</p>
<p class="response">
<input id="R010102" type="radio" value="B" name="R0101">
<label for="R010102">r12</label>
</p>
<p class="question">Q2</p>
<p class="response">
<input id="R010201" type="radio" value="A" name="R0102">
<label for="R010201">r2</label>
</p>
<p class="response">
<input id="R010202" type="radio" value="B" name="R0102">
<label for="R010202">r22</label>
</p>
<p class="submit">
<input type="submit" value="Votez">
</p>
</fieldset>

I want with jQuery, for each <p class="response"> retrieve the <p class="question"> juste before.

For example, if i have the response "r22" i want to retrieve Q2, if i have "r12" i want to retrieve Q1....

Thanks :)

Upvotes: 0

Views: 43

Answers (1)

Anton
Anton

Reputation: 32581

$('label:contains("r22")').prevAll('.question:first');

Try this out, this will get the first previous question for the label that contains r22

If you want to get the question dynamically use

$('.response').each(function(){
      console.log($(this).prevAll('.question:first'));
});

Upvotes: 1

Related Questions