Search code examples
javascriptappendappendchild

How to make a div element wrap other elements?(preudo selectors are present in code)


Here is a structure I am trying to reach:

<div class="images">
  <div class="image">
   <div class="box">
      ::before
      <a><img></a>
   </div>
  </div>
</div>

But I get:

<div class="images">
  <div class="image">
   <div class="box">::before</div>
      <a><img></a>       
  </div>
</div>

I tried many options but I can't make box div wrap a link and img. How can I do it?

 var image = document.createElement("div");
     image.className = "image";
 var images = document.createElement("div");
     images.className = "images";

 var foto = document.createElement("img"); 
 var a = document.createElement('a');

 a.appendChild(foto);

 var box = document.createElement('div');
     box.className = 'box';
     box.append(a)

     image.append(box);
     image.append(a);
     images.append(image);

Solution

  • You should use appendChild instead of append, so that the elements are actually appended inside each other and not after each other.

    Also, no need for image.append(a), as a will be appended to image along with box:

    //creating the elements
    var image = document.createElement("div");
    image.className = "image";
    
    var images = document.createElement("div");
    images.className = "images";
    
    var foto = document.createElement("img"); 
    var a = document.createElement('a');
    var box = document.createElement('div');
    box.className = 'box';
    
    //appending elements inside each other
    box.appendChild(a); //appendChild so that the <a> tag is *inside* the div
    a.appendChild(foto);
    image.appendChild(box);
    images.appendChild(image);
    
    //finally, appending everything to the body (for this example)
    document.body.appendChild(images);