我正在使用 DOMParser()
来解析 HTML 字符串,并尝试使用 for 循环获取所有子节点。但是我不知道如何获取子节点的节点及其子节点等...
var str = "<div><p>paragraph<span>span</span></p></div>";
var doc = new DOMParser().parseFromString(str, 'text/html');
var childnodes = doc.body.childNodes;
for (var i = 0; i < childnodes.length; i++) {
console.log(childnodes[i]);
console.log(childnodes[i].childNodes);
console.log(childnodes[i].childNodes[i].childNodes);
}
这如我所愿,它给出了 div
、p
、text
和 span
,但是我如何使用获取所有孙子的 for 循环来完成这项工作?没有 jQuery?
Here's a fiddle用上面的代码。
最佳答案
你应该为此使用递归:
function travelChildren(childnodes){
for (var i = 0; i < childnodes.length; i++) { // for each node in childnodes
console.log(childnodes[i]); // console log current node
travelChildren(childnodes[i].childNodes) // and travel its children
}
}
travelChildren(childnodes) // start recursion with the child nodes you want
关于javascript - 获得 childnodes child 直到没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32190102/