2017-06-08 58 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