EN
JavaScript - iterate text nodes only in DOM tree
5
points
In this short article, we want to show how to iterate over text nodes using JavaScript.

Practical example:
// ONLINE-RUNNER:browser;
const walkTextNodes = (node, filter) => {
const result = [];
const execute = node => {
let child = node.firstChild;
while (child) {
switch (child.nodeType) {
case Node.TEXT_NODE:
if (filter(child)) {
result.push(child);
}
break;
case Node.ELEMENT_NODE:
execute(child);
break;
}
child = child.nextSibling;
}
}
if (node) {
execute(node);
}
return result;
}
// Usage example:
const container = document.createElement('div');
container.innerHTML = `<p>This <u>is</u> example <b>text</b>.</p>`;
const filter = node => { // this filter removes text nodes that contains white characters only
return /^(\s|\n)+$/gi.test(node.data) ? false : true;
};
const nodes = walkTextNodes(container, filter); // 5 text nodes
for (const node of nodes) {
console.log(node.data);
}