为第二个孩子获取内在文本值

时间:2017-06-08 13:02:31

标签: javascript

我在使用

的门户产品中有以下代码



<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
&#13;
&#13;
&#13;

我需要以某种方式获取第二个孩子的文本内容(即本例中的(必需))。 我可以选择父元素而不会出现问题 var req = $(&#39;标签[for =&#34; Classification&#34;&#39;)但是无法找出如何选择所需的孩子并获得它的内容,因为我如果第二个子项为空()

,则只需要运行某些代码

1 个答案:

答案 0 :(得分:2)

您可以使用基于零的eq方法执行此操作:

var $secondSpan = $('label[for="Classification"] > span').eq(1);
$secondSpan.css('background-color','green')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
</label>

如果您愿意,可以使用:eq选择器

var $secondSpan = $('label[for="Classification"] > span:eq(1)');
$secondSpan.css('background-color','green')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
</label>

值得注意的是,:empty选择器也是如此:

var $secondSpan = $('label[for="Classification"] > span:eq(1)');
var isEmpty = $secondSpan.is(":empty");
console.log(isEmpty)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class ="control-label" for="Classification">
    <span>Classification</span>
    <span> (Required)</span>
</label>