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.
/
if you look at the jsfiddle above, I've used "appendChild". How e 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" mand.
Is this expected behavior?
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/sJg7E/
if you look at the jsfiddle above, I've used "appendChild". How e 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" mand.
Is this expected behavior?
Share Improve this question asked Aug 27, 2012 at 17:47 MoonMoon 22.6k72 gold badges198 silver badges276 bronze badges 3- appendchild won't clone a node. if you repeatedly appendchild the SAME node, then you're just moving it around. you need to clone THEN append to get new independent nodes. – Marc B Commented Aug 27, 2012 at 17:48
- 1 Well a node can only have one parent at a time, so if you append a node to a new parent then it can't have the old one as a parent anymore. – Pointy Commented Aug 27, 2012 at 17:48
- @Pointy // that makes more sense now. – Moon Commented Aug 27, 2012 at 17:49
1 Answer
Reset to default 10A 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744300949a4567497.html
评论列表(0条)