+ 1
AppendChild same element multiple times
Hi all, I am trying to understand how adding elements in JS works. In the snippet (which is the example given), I added a new element to be appended. I don't understand why if I change in the line 13, node1 to node, the text is not displayed, also why I can't add the same element multiple times. Changing for example, div.appendChild(p1); to div.appendChild(p);, the text is not displayed. https://code.sololearn.com/WNJqU58l7SOH#js In general, how is JS appending the elements? Can an element be added multiple times?
3 Réponses
+ 5
you can't have the same element in two places. but you can have different created elements with same content (text in this case). because in the DOM, being a tree of nodes, one node can have only one parent, it cannot have multiple parents.
this might help you understand clearer:
https://stackoverflow.com/questions/30667088/why-isnt-possible-to-append-a-same-child-in-two-dom-element
+ 2
if you after append a node3 to node... where do you append?
+ 2
You only can clone nodes
Eg.
var node2 = node1.cloneNode(true)
var p2 = p1.cloneNode(true)