Languages
[Edit]
EN

JavaScript - iterate text nodes only in DOM tree

5 points
Created by:
Dragontry
551

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:

// 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);
}
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