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
In this example, we create a reusable arrow function that walks through all text nodes of the passed node
element applying filter
function to them. In usage example section we also create filter that excludes all empty text nodes.
// 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);
}
Note:
The
walkTextNodes()
function needs to be executed after windowload
event or at the end of the script to make sure that all elements are loaded before the function execution.