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);}这是我的解决思路,但是结果不对,请大家提点一下。
1 回答
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
测试代码:
<!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
添加回答
举报
0/150
提交
取消