在jQuery中检索另一个之前的特定元素

时间:2012-11-13 10:17:28

标签: jquery dom element

我有一个像这样的HTML:

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

我想用jQuery,每个<p class="response">之前检索<p class="question"> juste。

例如,如果我有响应“r22”我想要检索Q2,如果我有“r12”我想要检索Q1 ....

谢谢:)

1 个答案:

答案 0 :(得分:1)

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

试试这个,这将获得包含r22

的标签的第一个上一个问题

如果您想动态使用

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