简体   繁体   中英

querySelectorAll to select only matching elements on top levels

By top levels, I mean the elements without any matching ancestors, like the span* in the following code snippet. How can I select only the span* s but not the span s?

span*
span*   
div
  span*
    span
    span   
  span*

There is no way, in selector syntax, to express "An element with no ancestors of the same type" (or even of a specific type).

The obvious approach to this would be to get every element and then recursively check all the ancestors to make sure that none have a matching tagName .

Note: this answer was originally an edit made by the OP to their question; I have merely moved it to its own answer.

I ended up using TreeWalker:

const nodes = [];
const treeWalker = document.createTreeWalker(rootNode, NodeFilter.SHOW_ELEMENT, {
   acceptNode: node => {
      if (node.matches(['span'])) {
         nodes.push(node);
         return NodeFilter.FILTER_REJECT;
      }
      nodes.push(node);
      return NodeFilter.FILTER_ACCEPT;
   }
});
while (treeWalker.nextNode()) { }
return nodes;

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