2

I have a couple of <div> like this:

<div>
    <div id='1'></div>
    <div id='2'></div>
    <div id='3'></div>
</div>

How can I create dynamically another div to cover div#1 and div#2 in JS or jQuery ?

<div id='event'>EVENT</div>

Thanks.

miami
  • 49
  • 5
  • 3
    Possible duplicate of [How to overlay one div over another div](https://stackoverflow.com/questions/2941189/how-to-overlay-one-div-over-another-div) – Claudia May 02 '18 at 01:59

2 Answers2

2

You can use wrapAll function provided by jQuery like

$("#1, #2").wrapAll( "<div class='new' id='event'>EVENT</div>");
.new{
  color : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
    <div id='1'>1..</div>
    <div id='2'>2..</div>
    <div id='3'>3..</div>
</div>

The .wrapAll() function can take any string or object that could be passed to the $() function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around all of the elements in the set of matched elements, as a single group.

Here for more details

Muhammad Usman
  • 10,039
  • 22
  • 39
0

I found this on Mozilla's doc page, describing the outerHTML attribute.

https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML

After you get the parts of the code you want to wrap, reassign it with a <div> on the front side of 1 and a </div> on the back side of 2.

d1 = document.getElementById('1');

d2 = document.getElementById('2');

d1.outerHTML = '<div>' + d1.outerHTML;

d2.outerHTML = d2.outerHTML + '</div>';

AndrewHK
  • 76
  • 3