+ 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?

20th May 2020, 3:13 PM
Sandra Meneses
Sandra Meneses - avatar
3 Answers
+ 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
20th May 2020, 3:32 PM
Sebastian Pacurar
Sebastian Pacurar - avatar
+ 2
if you after append a node3 to node... where do you append?
20th May 2020, 3:29 PM
Oma Falk
Oma Falk - avatar
+ 2
You only can clone nodes Eg. var node2 = node1.cloneNode(true) var p2 = p1.cloneNode(true)
20th May 2020, 4:01 PM
Calviղ - avatar