简体   繁体   English

使用jQuery在祖先和后代之间插入元素

[英]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. 我想保留对在此之前已设置的div的任何引用,因此只需执行$(“#outer”)。html($(“” + $(“#outer”)。html()+“” ))对我不起作用。 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? 有没有比创建中间div更好的方法,那就是将外部的所有子代移到中间div,然后将其附加到外部div?

Use .wrap() ... 使用.wrap() ...

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

DEMO: http://jsfiddle.net/ENmDF/ 演示: 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. 您应该注意,尽管jQuery看起来像您正在使用HTML,因为它接受了像'<div id="middle"></div>'这样的字符串来创建元素,但事实是,它需要您的字符串,使用它来创建DOM元素,然后将其插入DOM,并将其以及包装的部分放置在各自的位置。

It would be similar to this in the DOM API... 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/ 演示: http : //jsfiddle.net/ENmDF/1/


jQuery has another syntax for creating elements with attributes. jQuery具有用于创建具有属性的元素的另一种语法。 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/ 演示: 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. 它的工作方式与我的回答不是相同,但此方法使用DOM来创建将其包装的div元素。

Note the lack of a semicolon ( ; ) after setting the id attribute. 请注意,设置id属性后,缺少分号( ; )。

Demo . 演示

Also, in case you prefer it, here's a one-liner: 另外,如果您喜欢它,这里有一条线:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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