getElementsByTagName() equivalent for textNodes

前端 未结 7 963
日久生厌
日久生厌 2020-11-22 06:33

Is there any way to get the collection of all textNode objects within a document?

getElementsByTagName() works great for Elements, but

7条回答
  •  逝去的感伤
    2020-11-22 07:17

    Here's a modern Iterator version of the fastest TreeWalker method:

    function getTextNodesIterator(el) { // Returns an iterable TreeWalker
        const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
        walker[Symbol.iterator] = () => ({
            next() {
                const value = walker.nextNode();
                return {value, done: !value};
            }
        });
        return walker;
    }
    

    Usage:

    for (const textNode of getTextNodesIterator(document.body)) {
        console.log(textNode)
    }
    

    Safer version

    Using the iterator directly might get stuck if you move the nodes around while looping. This is safer, it returns an array:

    function getTextNodes(el) { // Returns an array of Text nodes
        const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
        const nodes = [];
        while (walker.nextNode()) {
            nodes.push(walker.currentNode);
        }
        return nodes;
    }
    

提交回复
热议问题