0

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>
2
  • To clarify - you are attempting to create the example structure up top (wrap > shelf > shelf-background > base) but are getting the flat structure at the bottom? I'd recommend reading how appendChild and append actually work. Commented Feb 4, 2020 at 18:04
  • @smashed-potatoes Yes, this is what I'm trying to do. Commented Feb 4, 2020 at 18:12

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.