首页 > 想要遍历文档中所有的文本节点,应该有什么样的解决思路?

想要遍历文档中所有的文本节点,应该有什么样的解决思路?

var allTextContent = new Array();  //存储所有文本节点的内容
function seachElemAllTextContent(node){
    for(var Pindex = 0 ; Pindex<node.length; Pindex++){
        node[Pindex] = removeWhitespace(node[Pindex]); //清除空白的文本节点
        var allnodeChildren = node[Pindex].childNodes;
        console.log(allnodeChildren);
        for(var i = 0;i<allnodeChildren.length;i++){
            while(allnodeChildren[i].childNodes.length>0){
                console.log(allnodeChildren[i]);
                seachElemAllTextContent(allnodeChildren[i]);
            }
            // if((allnodeChildren[i].nodeType==3)&&(/^\s+$/.test(allnodeChildren[i].nodeValue))){
            if((allnodeChildren[i].nodeType==3)&&(allnodeChildren[i].nodeValue!=' ')){
                allTextContent.push(allnodeChildren[i].nodeValue);
            }
        }
    }
    console.log(allTextContent);
}

这是我的解决思路,但是结果不对,请大家提点一下。


测试代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Javascript Test</title>
</head>
<body>
    <div>this is div
        <p>This is paragraph</p>
        <ul>this is ul
            <li>number1</li>
            <li>number2</li>
            <li>number3</li>
            <li>number4</li>
            <li>number5</li>
        </ul>
    </div>
    <script>
        var textArray = new Array();
        function search(element){
            var nodeList = element.childNodes;
            for (var i = 0; i < nodeList.length; i++) {
                    if (nodeList[i].nodeType == Node.TEXT_NODE && nodeList[i].nodeValue.trim() != "") {
                        textArray.push(nodeList[i].nodeValue);
                    } else if (nodeList[i].nodeType == Node.ELEMENT_NODE) {
                        search(nodeList[i]);
                    }
            }
        }
        search(document.body);
        console.log(textArray);
    </script>
</body>
</html>

测试结果:

[object Array]
[
      0: "this is div
        ",
      1: "This is paragraph",
      2: "this is ul
            ",
      3: "number1",
      4: "number2",
      5: "number3",
      6: "number4",
      7: "number5",
      8: "
        var textArray = new Array();
        function search(element){
            var nodeList = element.childNodes;
            for (var i = 0; i < nodeList.length; i++) {
                    if (nodeList[i].nodeType == Node.TEXT_NODE && nodeList[i].nodeValue.trim() != "") {
                        textArray.push(nodeList[i].nodeValue);
                    } else if (nodeList[i].nodeType == Node.ELEMENT_NODE) {
                        search(nodeList[i]);
                    }
            }
        }
        search(document.body);
        console.log(textArray);
    ",
      length: 9
   ]

测试环境:
Windows 7 Ultimate SP1
IE11

【热门文章】
【热门文章】