2017-06-08 62 views
0

我有一个门户产品中下面的代码我使用获取内部文本价值二孩

<label class ="control-label" for="Classification"> 
 
    <span>Classification</span> 
 
    <span> (Required)</span>

我需要以某种方式获得的第二个孩子的文本内容(即在这种情况下的(必需的) 我可以选择没有问题的父元素 var req = $('label [for =“Classification”'),但无法找出如何选择需要的子元素并获取其内容因为如果第二个孩子是空的,我只需要运行某些代码()

回答

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>

+0

的作品正是我需要它!谢谢!我将如何去取代那个孩子的内容? – Alex

+0

@Alex'.text()'或'.html()'代替'.css()'在我的前两个例子中。 – Jamiec

+0

非常感谢。正是我需要的 – Alex