views:

1106

answers:

3
A: 

Your line:

copyNode(toChild, fromChild);

should be

copyNode(fromChild, toChild);

When your function comes from recursion your fromChild element is empty...

Robert Koritnik
yes sir, i switched that too, it doesn't work.
nicko
A: 

As you move (not copy) the source nodes to the destination, they are removed from the list of childNodes on the source, and its length decreases.

You should use something like:

while (fromNode.firstChild) {
    toNode.appendChild(fromNode.firstChild);
}

instead.

Also, you don't need the recursion; when the node is moved, all its children will be moved with it.

NickFitz
thank you, sir, you saved me from brain-damage. i thought it was copying the node and not moving it because none of the functions explicitly specify the word move/copy. and i was always debugging to check the resultant node and never check what was happening to the source node. ty once again
nicko
A: 

Here is the way I would do it (which may or may not be preferred).

function copyElementChildren(fromNode,toNode){
    for (var i in fromNode.childNodes) {
        var node = fromNode.childNodes[i].cloneNode(true);
        toNode.appendChild(node);
    };
};

This uses cloning to copy it the element. The true in cloneNode(true) tells the browser to copy its attributes and childNodes as well.

thank you for the answer but i got this error in firefox "Error: fromNode.childNodes[i].cloneNode is not a function"i dint explore it further because the above solution worked, please let me know if you want me to debug the code with your solution.
nicko
That's interesting. I confess I didn't test the code since I've never actually needed to clone a node before. I took cloneNode from https://developer.mozilla.org/En/DOM/Node.cloneNode so I'm surprised it didn't work.