javascript - 获得 childnodes child 直到没有

标签 javascript html children domparser

我正在使用 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);
}

这如我所愿,它给出了 divptextspan ,但是我如何使用获取所有孙子的 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/

相关文章:

javascript - 关闭浏览器选项卡时打开模态框

javascript - 如何替换数字之间的字符串?

jquery - 如何在旋转木马中垂直居中随机高度的图像

jquery 选择具有某些属性的子级的父级

java - 我们如何使用 Linear 布局来代替 ListView

c# - WPF MenuItem 子项未显示

javascript - 删除:有人可以解释这种行为

javascript - 使用 Javascript 检查多维数组的长度

javascript - 如何设置背景图像

html - Flexbox 不适用于 IE10