TreeWalker Filters DOM Traversal

TreeWalker walks a subtree through a NodeFilter callback, so text extraction can drop regions like b-draft text without hand-written recursion.

JavascriptData Fetching

Code

javascriptsnippet
22 lines
// TreeWalker 带过滤器遍历子树,不用手写递归
const doc = new DOMParser().parseFromString(
  '<article>intro <span>hidden note</span> outro <b>draft</b></article>',
  'text/html',
);

const walker = doc.createTreeWalker(
  doc.body,
  NodeFilter.SHOW_TEXT,
  {
    acceptNode(node) {
      // <b> 里的文本整段丢弃,span 保留
      return node.parentElement?.closest('b')
        ? NodeFilter.FILTER_REJECT
        : NodeFilter.FILTER_ACCEPT;
    },
  },
);

const parts = [];
while (walker.nextNode()) parts.push(walker.currentNode.nodeValue);
console.log(parts.join('|'));

TreeWalker Filters DOM Traversal: the mechanics

The cycling part of this snippet is while (walker.nextNode()) parts.push(walker.currentNode.nodeValue);.

The file’s state is a handful of top-level bindings: doc, walker, parts.

Caveats

  • Everything it calls is documented as part of the language core.

Key statements

return node.parentElement?.closest('b')
  ? NodeFilter.FILTER_REJECT
  : NodeFilter.FILTER_ACCEPT;

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `doc`, `walker`, `parts`.