开发者

How to get all textNodes in HTML document from specific Tags using javascript?

How to get all textNodes from a group of specific tags say "blockquote,em,h4,h6,p" in a single array without using xpath or treewalker (IE do开发者_如何学Pythonesn't allow you to use xpath & treewalker)..please help me...its ok if the script is IE only.


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"]);


Use JQuery

$('blockquote,em,h4,h6,p').each(function(i, v) { alert(v); })

UPDATE, to get element text

$('blockquote,em,h4,h6,p').each(function(i, v) { alert(v.text()); })
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜