简体   繁体   English

为什么 append 不可能在两个 dom 元素中使用同一个子元素?

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

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. DOM是一个结构。

When you append an element, you change its parent.当你 append 一个元素时,你改变了它的父元素。

A node, in the browser, is much more than just the text inside your P (that string could be shared, in fact).浏览器中的节点不仅仅是 P 中的文本(实际上,该字符串可以共享)。 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.它还具有 position、尺寸、可见性、接收可能在子元素中触发的事件、将事件传播到其父元素等等。 Everything here depends on the position in the tree.这里的一切都取决于树中的 position。 Just like would many CSS selectors.就像许多 CSS 选择器一样。 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 haveto clone it .如果你想在两个地方有相同的内容,你必须克隆它

jQuery's appendTo() method inserts "every element in the set of matched elements to the end of the target". jQuery 的appendTo()方法将“匹配元素集中的每个元素插入到目标的末尾”。 Try this:尝试这个:

p.appendTo(".div-class1, .div-class2")

for AppendChild same element multiple times, we can use this way:对于 AppendChild 相同的元素多次,我们可以这样使用:

//main function
function appendChildMultiple(parent) {
  //check function argument is an element
  if (parent.nodeType !== undefined) {
    const pTag = document.createElement("p");
    pTag.innerText = "This is the appended element";
    //finally append child to parent
    parent.appendChild(pTag);
  }
}

and:和:

// target the wrapper and create test elements
const wrapper = document.querySelector(".wrapper");
const d1 = document.createElement("div");
const d2 = document.createElement("div");
//append test elements to wrapper
wrapper.appendChild(d1);
wrapper.appendChild(d2);

//use appendChildMultiple function
appendChildMultiple(d1);
appendChildMultiple(d2);
//we appended "pTag" multiple times

if we use Functions, we can AppendChild same element multiple times whitout cloneNode如果我们使用 Functions,我们可以在没有 cloneNode 的情况下多次 AppendChild 相同的元素

https://codepen.io/kiumad/pen/eYMNKYa https://codepen.io/kiumad/pen/eYMNKYa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM