getElementsByTagName() equivalent for textNodes

前端 未结 7 825
日久生厌
日久生厌 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:05

    Here's an alternative that's a bit more idiomatic and (hopefully) easier to understand.

    function getText(node) {
        // recurse into each child node
        if (node.hasChildNodes()) {
            node.childNodes.forEach(getText);
        }
        // get content of each non-empty text node
        else if (node.nodeType === Node.TEXT_NODE) {
            const text = node.textContent.trim();
            if (text) {
                console.log(text); // do something
            }
        }
    }
    

提交回复
热议问题