2012-03-31 79 views
2

如何選擇不包含任何元素的元素(使用jQuery)?選擇基礎元素?

例如,在下面的樹:

<div class="a"> 
    <div class="b"> 
     <div class="c"></div> 
    </div> 
    <div class="d"></div> 
    <div class="e">Lorem</div> 
</div> 

只有<div> s的classcd,和e將被選中。

回答

3
$(':not(:has(*))')... 

LIVE DEMO

使用filter函數來做到這一點,請注意> element將在ne xt jQuery版本!

您可以使用此:

$(':empty')... 
:因爲在 <div class="e">

使用:empty選擇文本節點

$('*').filter(function(){ 
     return $('*', this).length == 0 
    }) 

:empty選擇不會在這裏工作

docs

描述:選擇有沒有孩子(包括文本節點)的所有元素。

+1

不適用於'

Lorem
'。 – 2012-03-31 23:07:21

+0

@Derek。檢查更新。不錯,乾淨 – gdoron 2012-03-31 23:13:53

+0

這很簡單,我理解。 – 2012-03-31 23:21:37

3

試試這個:

$('*').filter(function() { 
    return $(this).children().length == 0; 
}); 

您還可能能夠使用過濾函數內(快)原生訪問DOM:如果你想

return this.children.length == 0; 
+2

你剛剛重新發明了輪子...... :) – gdoron 2012-03-31 23:05:49

+0

不是'$('> *',this).length == 0' return'true'? – 2012-03-31 23:06:13

+0

@Derek:你究竟是什麼意思? – ThiefMaster 2012-03-31 23:08:55