为什么不能在两个dom元素中追加同一个孩子?(Why isn't possible to append a same child in two dom element?)

181 IT屋

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 ?

解决方案

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.

我只是注意到我做不到



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

d1.appendChild(p); // d1现在是p
d2.appendChild(p); // d2现在是p $ $ $ b //但是d1中的p是多少?


有些人会说这是逻辑,但是,当我第一次注意到我认为它是多么冷酷时。



为什么不可能?


解决方案

DOM 结构。



附加元素时,更改其父元素。



浏览器中的节点很多不仅仅是P中的文本(实际上该字符串可以共享)。它还具有位置,维度,可见性,接收可能在子元素中触发的事件,将事件传播到其父元素,等等。这里的一切都取决于树中的位置。就像许多CSS选择器一样。想象它在两个地方是相同的元素并没有多大意义,最好将它看作两个节点,可能有一些相同的内容。



如果你想在两个地方拥有相同的内容,你有克隆它


本文地址:IT屋 » 为什么不能在两个dom元素中追加同一个孩子?