Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't possible to append a same child in two dom element?

Tags:

javascript

I just notice I couldn't do

var d1 = document.createElement('div');
var d2 = document.createElement('div');
var p = document.createElement('p');

d1.appendChild(p); // d1 has p now
d2.appendChild(p); // d2 has p now
// but where is p in d1 ?

Some would say it's logic, but well, when I first noticed that I thought how uncool it was.

Why isn't that possible ?

like image 419
vdegenne Avatar asked Jun 05 '15 12:06

vdegenne


People also ask

Can you append multiple children at once?

To append multiple child elements with JavaScript, we can use the append method. Then we write: const listElement = document. querySelector('ul') const listItem = document.

How do you append a child element?

Use appendChild() method to add a node to the end of the list of child nodes of a specified parent node. The appendChild() can be used to move an existing child node to the new position within the document.

What does append child method perform?

The appendChild() method appends a node (element) as the last child of an element.


1 Answers

The DOM is a tree structure.

When you append an element, you change its parent.

A node, in the browser, is much more than just the text inside your P (that string could be shared, in fact). It also has a position, dimensions, a visibility, receives events that could have been fired in child elements, propagate events to its parent, and so on. Everything here depends on the position in the tree. Just like would many CSS selectors. It doesn't make a lot of sense to imagine it's the same element at two places, it's better to think about it as two nodes, with maybe some identical content.

If you want to have the same content at two places, you have to clone it.

like image 161
Denys Séguret Avatar answered Nov 14 '22 19:11

Denys Séguret