I would like to convert
<div id="outer">
<div id="inner1"></div>
<div id="inner2"></div>
</div>
into
<div id="outer">
<div id="middle">
<div id="inner1"></div>
<div id="inner2"></div>
</div>
</div>
I would like to preserve any references to the inner divs that may have been set prior to this so just doing $("#outer").html($("<div id='middle>" + $("#outer").html() + "</div>")) will not work for me.
Is there a better way than just creating the middle div, moving all the children of outer to it and then appending it to the outer div?
Like this…
DEMO: http://jsfiddle.net/uy6wg/
The
.wrapInner()method will wrap all the content of#outerin the element you give it.This will include inner text nodes if your actual content contains any.
If you care about performance, here’s a native DOM solution…
DEMO: http://jsfiddle.net/uy6wg/1/
This could be made into a reusable function…
DEMO: http://jsfiddle.net/uy6wg/2/