Is there any way to get the collection of all textNode
objects within a document?
getElementsByTagName()
works great for Elements, but
Here's an alternative that's a bit more idiomatic and (hopefully) easier to understand.
function getText(node) {
// recurse into each child node
if (node.hasChildNodes()) {
node.childNodes.forEach(getText);
}
// get content of each non-empty text node
else if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent.trim();
if (text) {
console.log(text); // do something
}
}
}