replaceWith()
用提供的内容替换集合中所有匹配的元素并且返回被删除元素的集合。
.replaceWith()可以从DOM中移除内容,然后在这个地方插入新的内容。
通过调用replaceChild处理即可,但是这里需要注意的问题,就是事件的处理,因为节点的变更所以涉及到要移除这个节点的数据cleanData方法。
replaceWith: function() {
var arg = arguments[0];
this.domManip(arguments, function(elem) {
arg = this.parentNode;
jQuery.cleanData(getAll(this));
if (arg) {
arg.replaceChild(elem, this);
}
});
return arg && (arg.length || arg.nodeType) ? this : this.remove();
}
.replaceWith()方法,和大部分其他jQuery方法一样,返回jQuery对象,所以可以和其他方法链接使用,但是需要注意的是:对于该方法而言,该对象指向已经从 DOM 中被移除的对象,而不是指向替换用的对象。
删除目标节点
jQuery( this ).remove();
然后再插入一个新节点
parent.insertBefore( elem, next );
将匹配元素集合从DOM中删除要涉及到empty,remove,detach方法。
<!doctype html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <script src="http://code.jquery.com/jquery-latest.js"></script> <title>DOM操作</title> </head> <body> <button id="test1">模拟replaceWith处理</button> <div class="container"> <div class="inner first">Hello</div> <div class="inner second">And</div> <div class="inner third">Goodbye</div> </div> <script type="text/javascript"> //$('div.second').replaceWith('<h2>New heading</h2>'); $('#test1').click(function() { var elem = document.querySelectorAll('div.second')[0] var div = document.createElement('div') div.innerHTML = 'replaceWith处理' elem.parentNode.replaceChild(div, elem) }) </script> </body> </html>