简体   繁体   中英

Recursive appending of Node tree

I'm trying to append a node tree to the Dom , the dom tree is created via createHTMLDocument, my first approach was something like this: (doc is the node tree)

while(doc.head.children.length > 0){
        iframewin.document.head.appendChild(doc.head.children[0]);
    }
    while(doc.body.children.length > 0){
        iframewin.document.body.appendChild(doc.body.children[0]);
    }

this approach work well but on my case before i append each node i need to be able to do some changes on each node and the problem occurs when i'm having some nodes with descendants and i'm actually appending the entire node with its descendants , so i need to use importNode to copy the parent node without its descendants and than start appending its descendants to it and if its descendants have descendants than.....

so i need to do this recursively but unfortunately i don't really know how, i would love to see some examples :)

Your problem then is how to walk you node tree recursively to produce a modified node tree. It can be done this way:

function transformTree(inputTree, outputTree) {
    if (!inputTree.children) { 
        return;
    }
    for (let i = 0; i < inputTree.children.length; i++) {
        var inputNode = inputTree.children[i];
        var transformedNode = transformNode(inputNode);
        // recursiveCall
        tranformTree(inputNode, transformedNode);
        outputTree.appendChild(transformedNode);
    }
}

transformTree(doc.head, iframewin.document.head);
transformTree(doc.body, iframewin.document.body);

transformNode is the function doing "some changes" on each node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM