How can I insert existing elements into a dynamically created element using JavaScript?

You cannot inject any markup via CSS.
CSS is a stylesheet language, used to style documents written in HTML

However, you can create a new div element, append it to your page, then insert the existing div elements into it using JavaScript.

Here’s how:

var div = document.createElement('div'),
    divs = document.querySelectorAll('div'),
    len = divs.length,
    i;

// Set any necessary attributes
div.id = "myDiv";

for(i = 0; i < len; i++) {
  div.appendChild(divs[i]);
}

document.body.appendChild(div);

This will result in the desired markup:

<div id="myDiv">
  <div class="div 1">div 1</div>
  <div class="div 2">div 2</div>
  <div class="div 3">div 3</div>
  <div class="div 4">div 4</div>
  <div class="div 5">div 5</div>
</div>

Please note that document.querySelectorAll('div') selects any divs on the page. You will need to make this more specific to your case, e.g. document.querySelectorAll('div.myClass')

Leave a Comment