简体   繁体   中英

Exclude matched DOM & children from selection?

I'd like to select a set of elements and their children from the DOM.

Then, I would like to run a set of selections on the DOM that excludes those elements, as if they were removed.

.not() seems to match both parent elements and child elements and doesn't properly exclude.

.find(':not(.myclass)') returns a list of about a bajillion elements and doesn't properly exclude.

What's my trouble? This seems simple but the functions I expect to do this don't behave as I expect.

I thought about cloning the DOM, removing the elements, and then running my selection matches on the cloned DOM... but that seems bad . Like, a major performance hit.

What's the best way to do this?

Here's the code I have:

jQuery('html').not(".page-node,.quote").find(selector).each(function(){
//do stuff here to returned elements

.page-node is a body class and should return the body element on nearly all pages and exclude the selector from being matched on those pages.

Edit: I have created a jsFiddle to demonstrate what I'm talking about: http://jsfiddle.net/glassdimly/H4tJe/4/

Not() will work with an appropriate descendant selector . A * following any selector will match all descendants (children, grandchildren etc). By applying it in a not , you can ask that all descendants be excluded from the match. As you also want to exclude the parent, include that in the not as well:

eg

$(selector).not(".page-node,.page-node *,.quote,.quote *")

Which equates to: "Not has class page-node OR and child/descendant of page-node " or "Not has class quote OR any child/descendant of quote "

Updated JSFiddle: http://jsfiddle.net/TrueBlueAussie/H4tJe/7/

jQuery(document).find('.list').not('.exclude,.exclude *').each(function(){
    this.remove();
});

Which equates to "Find all items has class list , but exclude any that also have class exclude and also exclude any descendants of any element that has class exclude "

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