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...
$('#outer').wrapInner($('<div>',{id:'middle'}));
DEMO: http://jsfiddle.net/uy6wg/
The .wrapInner()
method will wrap all the content of #outer
in 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...
var outer = document.getElementById('outer'),
middle = document.createElement('div');
middle.id = 'middle';
while(outer.firstChild)
middle.appendChild(outer.firstChild);
outer.appendChild(middle);
DEMO: http://jsfiddle.net/uy6wg/1/
This could be made into a reusable function...
function wrapInner(id, tag) {
var outer = document.getElementById(id),
wrapper = document.createElement(tag);
while(outer.firstChild)
wrapper.appendChild(outer.firstChild);
outer.appendChild(wrapper);
return wrapper;
}
wrapInner('outer','div').id = "middle";
您可以使用.wrapAll()
方法 :
$("#outer > div").wrapAll('<div id="middle"></div>');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.