-5

I want to add a main DIV outside the individual many DIVs by CSS, so I can control the whole DIV by an ID.

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

I want to like this way:

<div id="myId">
   <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>

But I want to do this by CSS only because the html part is coming from third party, so I can't edit or add anything in the html. But I can edit by CSS.

Thanks in advance, :) taps

James Hibbard
  • 16,490
  • 14
  • 62
  • 74
taps
  • 31
  • 7

1 Answers1

0

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

James Hibbard
  • 16,490
  • 14
  • 62
  • 74