这是我的 HTML。我的目标是在 Javascript 中创建元素并将其插入到带有“wrap”类的 div 中,但没有成功。
<div class="wrap">
<div class="shelf">
<div class="shelf-background">
<div class="base">
</div>
</div>
</div>
</div>
var base = document.createElement('div');
var shelfBackground = document.createElement('div');
var wrap = document.querySelector(".wrap");
var shelf = document.createElement('div');
shelfBackground.className = "shelf-background";
base.className = "base";
shelf.className = "shelf";
shelfBackground.appendChild(base);
wrap.append(shelf, shelfBackground, shelfBackground.appendChild(base));
我得到
<div class="wrap">
<div class="shelf"></div>
<div class="shelf-background"></div>
<div class="base"></div>
</div>
现在,您将 base 附加到背景,然后将所有元素附加到wrap
顶层元素。另请注意,当您调用 时shelfBackground.appendChild(base)
,它会返回附加的子base
元素,这就是为什么它是输出结构中的最后一个元素。
您需要做的是将元素附加到它们各自的父元素上,即:
...
// Build the structure from the bottom up
shelfBackground.appendChild(base); // shelf-background > base
shelf.appendChild(shelfBackground); // shelf > shelf-background > base
wrap.appendChild(shelf); // wrap > shelf > shelf-background > base
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句