如何使用jQuery定位嵌套在另一个元素的同级标签中的元素

时间:2018-10-18 16:20:20

标签: jquery jquery-selectors

示例代码:

<input type="radio" id="option_1" name="radio_group" checked="checked" value="1">

<label for="option_1"><span class="categories_on_main_overlay">OPTION 1</span></label>

如何在jQuery中定位作为输入标签的同级标签的跨度文本(“ OPTION 1”)。

到目前为止,我已经尝试了以下我认为可行的方法,但是却一无所获:

$("input[name='radio_group']:checked").next('label').next('span').text();

1 个答案:

答案 0 :(得分:1)

您很近,但是您不想要第二个.next(),它会寻找同级并想要孩子。因此,请改用.find()

$("input[name='radio_group']:checked").next('label').find('span').text();

console.log($("input[name='radio_group']:checked").next('label').find('span').text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="option_1" name="radio_group" checked="checked" value="1">

<label for="option_1"><span class="categories_on_main_overlay">OPTION 1</span></label>