Lone Learner
Lone Learner

Reputation: 20698

Does .appendChild() kill the parent-child relationship between the child and its current parent?

When I do something like divNode.appendChild(pNode), the pNode is moved inside divNode. It seems like its parent changes from whatever it was to divNode. Is this an expected behavior?

Here is my code: http://jsfiddle.net/YqG96/

<html>
<head>
<style>
p {
    background: orange;
}
div {
    background: lightcyan;
    padding: 5px;
}
</style>
<script>
window.onload = function() {
    pNode = document.getElementById('pNode');
    divNode = document.getElementById('divNode');
    divNode.appendChild(pNode);
}
</script>
</head>
<body>
<p id="pNode">Foo</p>
<div id="divNode">Bar</div>
</body>
</html>

Is it possible to modify it so that pNode remains under the body as well as the divNode? If two parents for a node doesn't make sense, then is it possible to create a new copy of pNode and append this new copy to divNode?

Upvotes: 3

Views: 970

Answers (1)

jfriend00
jfriend00

Reputation: 707806

This is an expected behavior. When you do appendChild()on a node that is already in the DOM, the node is moved from where it currently is in the DOM to the new location you specify. That will change it's parent and the next and previous nodes too.

A node can only have one direct parent, so it is not possible to have two parents as each parent signifies a location for the node and, unlike in the mysteries of particle physics, a node can only be one place at a time. If you want two nodes in two locations, you can either create a new node and append that one or you can clone the existing node and append that one.

See the cloneNode() function for info about how to make a copy of the node and insert the copy in this second location.

<script>
window.onload = function() {
    pNode = document.getElementById('pNode').cloneNode(true);
    pNode.id = "pNode2";
    divNode = document.getElementById('divNode');
    divNode.appendChild(pNode);
}
</script>

Remember that when you clone nodes, any nodes in the cloned tree that had an ID will need a new ID so that ID values stay unique in the document.

Upvotes: 5

Related Questions