简体   繁体   English

如何删除jQuery组的其他成员的后代元素?

[英]How can I remove elements of a jQuery group that are descendants of other members?

Suppose I've collected a jQuery group of DOM nodes matching some selector, and the selector is such that it's possible that some of the matching nodes might be descendants of other matches, eg: 假设我已经收集了一个与某些选择器匹配的jQuery DOM节点组,并且选择器是如此,使得某些匹配节点可能是其他匹配项的后代,例如:

<div class="row">
    <!-- ... -->
    <div class="row"><!-- ... --></div>
    <!-- ... -->
</div>
<div class="row">
    <!-- ... -->
    <div class="row">
        <!-- ... -->
        <div class="row"><!-- ... --></div>
    </div>
    <div class="row"><!-- ... --></div>
    <!-- ... -->
</div>
$rows = $('.row');

Now suppose that the action I'm going to take will affect each node's entire subtree, and I need to be sure that I act on any given DOM node at most once. 现在假设我将要执行的操作将影响每个节点的整个子树,并且我需要确保我最多对任何给定的DOM节点执行一次操作。 How would I remove all elements of my group that are descendants of other members of the same group? 如何删除组中属于同一组其他成员后代的所有元素?

The simplest and cleanest way I've found to accomplish this is to combine the behaviors of $.fn.not() and $.fn.find() : 我发现最简单,最干净的方法是结合$.fn.not()$.fn.find()

var $rows = $('.row');
$rows = $rows.not($rows.find($rows));

$elems.find($elems) will return all members of $elems that are descendants of one or more members of $elems (not including the element itself, so no worries there). $elems.find($elems)将返回所有成员$elems是一个或多个成员的后代$elems (不包括元素本身,所以不用担心有)。 $elems.not(group) will return a only the members of $elems that are not in group . $elems.not(group)将仅返回不在group$elems group Together, this will find all members of $elems that are children of other members, then return everything else. 在一起,这将找到$elems所有其他成员的所有成员,然后返回其他所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM