js获取结构化字典中的节点

js get nodes in a structured dictionary

我想获取结构化字典中特定父元素的所有节点。例如,使用以下 HTML:

<div id="wrapper">
    <h1>
        <a href="#"></a>
        <p></p>
    </h1>
    <span></span>
    <form>
        <div>
            <h2></h2>
            <label>
                <input type="text">
            </label>
        </div>
        <div>
            <button></button>
        </div>
    </form>
    <span></span>
</div>

预期输出为:

{
    "div": [
        {"h1": [
            "a",
            "p",
        ]},
        "span",
        {"form": [
            {"div": [
                "h2",
                {"label": ["input"]},
            ]},
            {"div": ["button"]},
        ]},
        "span",
    ],
}

如有任何建议,我们将不胜感激。


更新

这个函数用来操作父子;

// func takes a parent and a child as param
function recursor(parent, node, func){
    if(node.children.length){
        for(let ii = 0; ii < node.children.length; ii++){
            recursor(node, node.children[ii], func);
        }
    }else{
        func(parent, node);
    }
}

您可以使用递归函数执行此操作,将 DOM 结构(它是一个简化)转换为您的目标结构:

const getTree = root => root.children.length 
        ? {
              [root.tagName.toLowerCase()]: Array.from(root.children, getTree)
          } 
        : root.tagName.toLowerCase();

const result = getTree(document.getElementById("wrapper"));

console.log(result);
<div id="wrapper">
    <h1>
        <a href="#"></a>
        <p></p>
    </h1>
    <span></span>
    <form>
        <div>
            <h2></h2>
            <label>
                <input type="text">
            </label>
        </div>
        <div>
            <button></button>
        </div>
    </form>
    <span></span>
</div>