I would like to convert
<div id="outer">
<div id="inner"></div>
</div>
into
<div id="outer">
<div id="middle">
<div id="inner"></div>
</div>
</div>
I would like to preserve any references to the divs that may have been set prior to this so just doing $(“#outer”).html($(“” + $(“#outer”).html() + “”)) 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?
Use
.wrap()…DEMO: http://jsfiddle.net/ENmDF/
You should note that although jQuery makes it look like you’re working with HTML since it accepts a string like
'<div id="middle"></div>'to create an element, the truth is that it takes your string, uses it to create DOM elements, then inserts it into the DOM, placing it, and the wrapped part, in their respective places.It would be similar to this in the DOM API…
DEMO: http://jsfiddle.net/ENmDF/1/
jQuery has another syntax for creating elements with attributes. That is to pass an object as the second argument to the
$function, so the original code could be written like this…DEMO: http://jsfiddle.net/ENmDF/3/