2010-03-31 49 views
2
<div> 
    <div>test</div> 
</div> 

$("div:contains('test')").css('display','none'); 

我知道我要在這個上踢自己。問題是,當這個運行時,所有div由於嵌套而被隱藏。我如何做到這一點,使父母的div不會被隱藏起來?我僅限於使用1.2.6試圖在嵌套的div中使用包含選擇器

回答

3
$("div:contains('test'):not(:has(div))").hide(); 
+0

傳說,這將做的工作。謝謝! – Dtour 2010-03-31 08:22:58

1

如果您想要一個優雅的解決方案,請定義一個新的選擇器。不幸的是,:empty是不夠的,因爲任何帶有文本節點的子節點都不是空的。

$.extend($.expr[':'], { 
    leaf: function(elem, i, match) { 
    return $(elem).children().length == 0; 
    } 
}); 

然後你就可以這樣做:

$("div:leaf:contains('test')").hide();