如何在 JavaScript 中创建嵌套元素?

How to create nested elements in JavaScript?

这是我的 HTML。我的目标是在 Javascript 中创建元素并使用 class "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) 时,它 returns 附加的子 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

试试这个:

var wrap = document.querySelector(".wrap");

var base = document.createElement('div');
var shelfBackground = document.createElement('div');
var shelf = document.createElement('div');

base.className = "base";
shelfBackground.className = "shelf-background";
shelf.className = "shelf";

shelfBackground.appendChild(base);
shelf.appendChild(shelfBackground);
wrap.appendChild(shelf);
document.appendChild(wrap);