Is there any way to get the collection of all textNode objects within a document?
getElementsByTagName() works great for Elements, but
Here's a modern Iterator version of the fastest TreeWalker method:
function getTextNodesIterator(el) { // Returns an iterable TreeWalker
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
walker[Symbol.iterator] = () => ({
next() {
const value = walker.nextNode();
return {value, done: !value};
}
});
return walker;
}
Usage:
for (const textNode of getTextNodesIterator(document.body)) {
console.log(textNode)
}
Using the iterator directly might get stuck if you move the nodes around while looping. This is safer, it returns an array:
function getTextNodes(el) { // Returns an array of Text nodes
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
const nodes = [];
while (walker.nextNode()) {
nodes.push(walker.currentNode);
}
return nodes;
}