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

When I do something like divNode.appendChild(pNode)

, it pNode

moves inside divNode

. It seems that his parental changes have changed from before divNode

. Is this the 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 change it so that it pNode

stays under the body as well divNode

? If two parents for a node don't make sense, then is it possible to create a new copy pNode

and add that new copy to divNode

?

+3


source to share


1 answer


This is expected behavior. When you execute appendChild()

on a node that is already in the DOM, the node is moved from where it is currently in the DOM to the new location you specify. This will change it to both parent and next and previous nodes.

A node can only have one direct parent, so it is not possible to have two parents, since each parent means a location for a node and, unlike the mysteries of particle physics, it is only possible for a node to be one location at a time. If you need two nodes in two places, you can either create a new node or add it, or you can clone an existing node and add it.

See the cloneNode()

function
for information on how to make a copy of a node and insert the copy in second place.



<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 with an ID must have a new ID for the ID values ​​to remain unique across the document.

+5


source







All Articles