javascript - Why does "appendChild" moves a node? - Stack Overflow

I'm playing around with native javascript. I'm basically practicing basic node manipulations

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
Add a ment  | 

1 Answer 1

Reset to default 10

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744300949a4567497.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信