2017-06-19 45 views

回答

6

它就在那裏的文檔中::first-child

說明:選擇是他們的父母的第一個孩子的所有元素。

演示:

$('div:first-child').css({border: '1px solid'});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <div>I am a first child</div> 
 
    <div>I am a second child 
 
    <div> I am a nested first child</div> 
 
    <div> I am a nested second child</div> 
 
    </div> 
 
</div> 
 
<div>Yet another div child of the body</div>

0

如果你使用jQuery,您可以只針對類名,它會拋出的所有實例運行到了一個數組 - 無論深度。

例如:

var children = $('.childclass'); 
console.log(children.length)//returns "3". 
$(children[1]) //returns the second "childclass" instance 
$(children[1]).css('color', 'red'); //will give the 2nd instance of the childclass red text. 

https://jsfiddle.net/z1djzo2n/

<div class="topclass"> 
    <div class="childclass"> 
     <div class="someotherclass"></div> 
     <div class="childclass"></div> 
    </div> 
    <div class="childclass"></div> 
</div> 

否則,如果你要單獨針對他們沒有jQuery的那樣,你可以使用:第一胎選擇。

+0

'children [1]'返回一個dom元素...不是jQuery對象。不能在dom元素上使用'css()'。另外'長度'是一個屬性不是函數 – charlietfl

+0

你是對的 - 我忘了把返回包裝在一個jQuery對象中。更新了我的答案。 – Korgrue

+0

爲什麼這樣做?可以使用'eq()'代替。無論哪種方式,這不會做OP所要求的 – charlietfl