javascript/ jquery/ dom

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";

DEMO: http://jsfiddle.net/uy6wg/2/

您可以使用.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.

Related Question Insert element between ancestor and descendant using jQuery What's the best way to select an element between one element and one of its ancestor using jQuery Select multiple descendants with jQuery? jQuery descendants selector with multiple selector jQuery set ancestor element for scope Insert multiple values across multiple element in jQuery here to insert element using jQuery How can i insert html element between start and end tag of another html element using jquery jQuery Traversal — Find an Element Relative to Common Ancestor Insert HTML element between multiples li in jQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM