且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用javascript从特定的标签获取HTML文档中的所有textNodes?

更新时间:2023-02-19 17:07:51

以下将让你所有的文本节点包含在匹配元素中:

The following will get you all text nodes that are contained within a matching element:

function getTextNodes(root, tagNamesArray) {
    var textNodes = [];
    var regex = new RegExp("^(" + tagNamesArray.join("|") + ")$", "i");
    var insideMatchingElement = false;

    function getNodes(node, insideMatchingElement) {
        if (node.nodeType == 3 && insideMatchingElement) {
            textNodes.push(node);
        } else if (node.nodeType == 1) {
            var childrenInsideMatchingElement = insideMatchingElement || regex.test(node.nodeName);
            for (var child = node.firstChild; child; child = child.nextSibling) {
                getNodes(child, childrenInsideMatchingElement);
            }
        }
    }

    getNodes(root);
    return textNodes;
}

var textNodes = getTextNodes(document.body, ["blockquote","em","h4","h6","p"]);