createTreeWalker DOM API All In One
document.createTreeWalker()
createTreeWalker(root)
createTreeWalker(root, whatToShow)
createTreeWalker(root, whatToShow, filter)
https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker
The TreeWalker
object represents the nodes of a document subtree
and a position
within them.
A TreeWalker
can be created using the Document.createTreeWalker()
method.
https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
},
},
false,
);
nodeFilter = treeWalker.filter; // document.body in this case
NodeFilter.SHOW_ALL
NodeFilter.SHOW_ELEMENT
NodeFilter.SHOW_TEXT
NodeFilter.SHOW_COMMENT
...- NodeFilter.SHOW_DOCUMENT
- NodeFilter.SHOW_DOCUMENT_TYPE
- NodeFilter.SHOW_DOCUMENT_FRAGMENT
- NodeFilter.SHOW_PROCESSING_INSTRUCTION
https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker/filter
https://caniuse.com/?search=createTreeWalker
demos
https://codepen.io/xgqfrms/pen/eYbmBJL
const content = document.getElementById('content');
// filter
const treeWalker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
console.log(`treeWalker =`, treeWalker);
let node;
// text
while (node = treeWalker.nextNode()) {
console.log(`node =`, node, node.nodeValue.trim());
pre.insertAdjacentHTML(`beforeend`, `<p>${node.nodeValue.trim()}</p>`)
}
<div id="content">
<p>This is a <span>paragraph</span> with some <em>emphasis</em>.</p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
</ul>
</div>