brad_fresh
brad_fresh

Reputation: 129

How to create nested elements in JavaScript?

Here's my HTML. I target to create elements in Javascript and insert it into div with the class "wrap" but didn't succeed.

<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));

I get

   <div class="wrap">
     <div class="shelf"></div>
        <div class="shelf-background"></div>
     <div class="base"></div>
   </div>

Upvotes: 0

Views: 2552

Answers (2)

Lucien
Lucien

Reputation: 13

Try this:

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);

Upvotes: 1

smashed-potatoes
smashed-potatoes

Reputation: 2222

Right now, you are appending base to the background, and then appending all of the elements to the wrap element at the top level. Also note, when you call shelfBackground.appendChild(base), it returns the appended child base which is why it is the last element in your output structure.

What you need to do is instead append the elements based to their respective parents, i.e.:

...
// 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

Upvotes: 1

Related Questions