2011-12-05 44 views
4

我想只選擇給定類型的子元素的第一個「圖層」,但不是嵌套在另一個限定元素內的元素。例如。在:jQuery/JavaScript:僅選擇兒童的第一個「圖層」

<div id='top'> 
    <div id="s1" class="special"> 
    <div id="s2" class="special"></div> 
    </div> 
    <div> 
    <div id="s3" class="special"></div> 
    </div> 
</div> 

我想找到#S1和S3#,而不是#S2,用類似$( '#' 頂部)找到( '特殊:not_nested')。 jQuery有可能嗎? XPATH?

我想到了像expr [':']。not_nested這樣的jQuery自定義過濾器,但無法弄清楚如何考慮頂級父級(在這種情況下爲$('#top')),因爲有可能成爲#top的母鏈中的其他特殊類別。

我現在應該提及我正在使用遞歸調用$ .fn.children(),我認爲這不是很有效。

[EDIT2]測試工作代碼:

var node = $('#top'), 
    result = (node.find('.special').filter(function(){ 
     return !($(this).parent().closest(".special", node).length); 
    })); 

但是,如果 「#top返回」 有。特別類本身這不起作用。因此,也許這樣的:

var node = $('#top'), 
result= node.find('.special').filter(function(){ 
    var parent = $(this).parent().closest(".special", node); 
    return !parent.length || parent.is(node); 
}); 

回答

3

另一種選擇是使用.children()代替.find(),但它會與idrumgood的解決方案具有相同的結果。

$('#top').children('.special') 

編輯:我剛剛意識到的#s3嵌套,這可能對這種情況的工作:

$('#top').find('.special').filter(function(){ 
    return $(this).closest('.special').length === 0; 
}).doSomething() 

EDIT2:這裏亞去:

$('#top').find('.special').filter(function(){ 
    return !$(this).parent().closest(".special").closest("#top").length; 
}).doSomething; 
+0

http://api.jquery.com/children/ – Dave

+0

這不會發揮作用,因爲它只發現直接的孩子,我需要找到孫子們,只要他們沒有嵌套在「特殊」的另一個孩子/孫子之下, 。 – user1066127

+0

檢查我的編輯,它爲此添加了一個檢查 –

3

$('#top > .special');>只有直接後代。

除了你的代碼有#s3也嵌套在一個輔助div中,所以我不確定你是否真的想要你的問題。

+0

#S3沒有嵌套在另一個 「特別」 分區。我試圖選擇unnested「.specials」,而不是unnested divs。這就是這個問題的原因...... – user1066127

+0

查看凱文B的答案。在.filter函數中使用一個函數來測試一個.special父級應該做的訣竅 – idrumgood

+0

請看凱文B的回答下我的評論爲什麼過濾器不起作用。我原來的問題的最後一部分也解釋了它。 – user1066127

0

如果它是具體的申報單,你可能想嘗試使用帶有空格的css選擇器,如

".one .three" and ".one" 

這樣的事情

<div class="one"> 
    <div class="two"> 
     <div class="three">