replaceWith自动关闭标记

我有3个div,我想用另一个div的开始标记替换第一个div,用结束标记替换第三个div。 这就是我的意思:

1
2
3

当我尝试用

替换第一个div(使用replaceWith())而第三个用

替换时,jQuery有点误解为:

 
2

虽然我真正想要的是:

 
2

先感谢您,

您应该使用整个元素而不是HTML代码。 另一种思考方式是:

 // Get the div you want var good = $('div:eq(1)'); // Remove the others $('div').not(good).remove(); // Wrap the div you want good.wrap('
');

如果第一个和最后一个之间有多个div,您可以这样做:

 $('div:first').replaceWith('
'); $('div.foo').nextAll('div').appendTo('div.foo'); $('div.foo :last').remove();

见演示: http : //jsfiddle.net/TBMHt/