2010-10-19 44 views
2

我有這樣的HTML:jQuery選擇對每位父母各第一要素

<div class="container"> 
    <span class="iconset"></span> <!-- want to select --> 
    <span class="iconset"></span> 
</div> 
<div class="container"> 
    <span class="iconset"></span> <!-- want to select --> 
    <span class="iconset"></span> 
</div> 

,我需要選擇每一個.container的第一要素,使用:

$(".container .iconset:first"); 

我得到的只有一個元素,第一次被發現。並使用

$(".container .iconset"); 

我得到所有4個元素。我不想檢查索引是偶數還是奇數,因爲稍後可能會添加更多元素。

我該如何構建一個選擇器來返回每個容器上的所有第一個元素?

回答

8

這使用the first child selector,它將只選擇.iconset如果它是其父項的第一個子項。

它還使用>孩子選擇,因爲.iconset.container直接孩子。

$(".container > .iconset:first-child"); 

您使用the first selector,這縮小了整個匹配組下到第一個。

+0

我記得看到這個,但我從來沒有下過來看看它做什麼。謝謝!還要添加nth-child:http://api.jquery.com/nth-child-selector/ – BrunoLM 2010-10-19 13:34:53

+0

@Bruno - 不客氣。是的,第n孩子也可以使用。 :O) – user113716 2010-10-19 13:46:48