[英]jquery selecting children not nested in a child
我有一個jQuery選擇器的問題。
假設我有以下html,其中(...)
代表未定義數量的html標簽。
(...)
<div class="container">
(...)
<div class="subContainer">
(...)
<div class="container">
(...)
<div class="subContainer"/>
(...)
</div>
(...)
</div>
(...)
</div>
(...)
假設我有一個名為container
的javascript變量指向第一個div(帶有類容器)。 我想要一個jquery來選擇第一個子容器而不是嵌套的子容器。 如果我使用$(".subContainer", container);
我會得到他們兩個。
我試過用了
$(".subContainer:not(.container .subContainer)", container);
但這會返回一個空集。 有解決方案嗎
謝謝。
您可以使用direct child
選擇器:
$("> .subContainer", container);
如果container
是引用頂級.container
元素的jQuery對象,您還可以使用children
方法:
container.children('.subContainer');
或find
和first
方法:
container.find('.subContainer').first();
基於Jquery:獲取一個類的所有元素,這些元素不是具有相同類名的元素的后代? 我開發了以下解決方案。 謝謝大家。
$.fn.findButNotNested = function(selector, notInSelector) {
var origElement = $(this);
return origElement.find(selector).filter(function() {
return origElement[0] == $(this).closest(notInSelector)[0];
});
};
要獲得第一個subContainer,您可以使用
$('.subContainer')[0]
這似乎適合我自己的用途......
$('.item').filter(function() { return $(this).parents('.item').length == 0; });
這只返回#outer
div。
<div class="item" id="outer">
<div class="item" id="inner"></div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.