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:

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


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



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()

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

window.onload = function() {
    pNode = document.getElementById('pNode').cloneNode(true); = "pNode2";
    divNode = document.getElementById('divNode');


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.



All Articles