简体   繁体   中英

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:

<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. 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() :

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.not(group) will return a only the members of $elems that are not in group . Together, this will find all members of $elems that are children of other members, then return everything else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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