Sunil Chaudhry Sunil Chaudhry - 3 months ago 8
jQuery Question

Add a parent div for existing divs

I have 2 divs(dynamically created) , I want to add a parent div for these existing divs.

HTML:-

<div id="a">div1</div>
<div id="b">div2</div>


Output should be like this :-

<div id="1">Main Div
<div id="a">div1</div>
<div id="b">div2</div>
</div>

Answer

Use .wrapAll() - which wrap an HTML structure around all elements in the set of matched elements.

$( ".inner" ).wrapAll( "<div id='1' />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="inner" id="a">div 1</div> 
<div class="inner" id="b">div 2</div> 

Comments