简体   繁体   中英

Insert element between ancestor and descendant using jQuery

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() ...

$('#inner').wrap('<div id="middle"></div>');

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...

var inner = document.getElementById('inner');
var middle = document.createElement('div');
middle.id = 'middle';

inner.parentNode.insertBefore(middle, inner);

middle.appendChild(inner);

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...

$('#inner').wrap($('<div>', {id:"middle"}));

DEMO: http://jsfiddle.net/ENmDF/3/

$("#inner")
    .wrap(
        $("<div>")
            .prop("id", "middle")
    );

Works the same way as am not i am's answer, but this one uses the DOM to create the div element that wraps it.

Note the lack of a semicolon ( ; ) after setting the id attribute.

Demo .

Also, in case you prefer it, here's a one-liner:

$("#inner").wrap($("<div>").attr("id","middle"));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM