问题
I'm playing around with native javascript. I'm basically practicing basic node manipulations such -- add, remove, move, copy, and create.
While testing move, I got a question.
http://jsfiddle.net/sJg7E/
if you look at the jsfiddle above, I've used "appendChild". How come it moves a node to a new div? I know that I need to clone a node if I want to copy a node. It just doesn't look/sound right with "appendChild" command.
Is this expected behavior?
回答1:
A node can only have one parent. Therefore it moves it if you appends it to another node.
From documentation of appendChild:
Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.
From the same page:
You can use cloneNode to make a copy of the node before appending it under the new parent. (Note that the copies made with cloneNode will not be automatically kept in sync.)
Also note:
This method is not allowed to move nodes between different documents. If you want to append node from a different document (for example to display results from AJAX request) you must first use importNode.
You can also read the w3c specification of appendChild:
Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.
来源:https://stackoverflow.com/questions/12146888/why-does-appendchild-moves-a-node