Languages
[Edit]
EN

JavaScript - iterate text nodes only in DOM tree

5 points
Created by:
Dragontry
731

In this short article, we want to show how to iterate over text nodes using JavaScript.

Iterate over text nodes using JavaScript.
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 window load event or at the end of the script to make sure that all elements are loaded before the function execution.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join