Languages
[Edit]
EN

JavaScript - find all text nodes on web page

0 points
Created by:
Adnaan-Robin
724

In this article, we would like to show you how to find all text nodes on web page 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. At the end, we call the walkTextNodes() function on window load event.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <h1>Header</h1>
  <div>Div</div>
  <script>

    function walkTextNodes(node, filter) {
        var result = [];
        function execute (node) {
            var 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:

    var container = document.body;

    function filter(node) { // this filter removes text nodes that contains white characters only
        return /^(\s|\n)+$/gi.test(node.data) ? false : true;
    };
    
    window.addEventListener('load', function() {
        var nodes = walkTextNodes(container, filter);
        for (var i = 0; i < nodes.length; ++i) {
            console.log(nodes[i].data);
        }
    });

  </script>
  <p>Paragraph</p>
  <span>Span</span>
</body>
</html>

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.

Note:

The <script> element content is being displayed because the interpreter treats it a text node.

 

See also

  1. JavaScript - iterate text nodes only in DOM tree

References

  1. Node.firstChild - Web APIs | MDN
  2. Node.nextSibling - Web APIs | MDN
  3. Node.nodeType - Web APIs | MDN
  4. RegExp.prototype.test() - JavaScript | MDN
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