我有3个div,我想用另一个div的开始标记替换第一个div,用结束标记替换第三个div。这就是我的意思:
<div>1</div>
<div>2</div>
<div>3</div>
当我尝试替换(使用replaceWith())第一个div为<div class="foo">
而第三个为</div>
时,jQuery有点误解为:
<div class="foo"></div>
<div>2</div>
</div>
虽然我真正想要的是:
<div class="foo">
<div>2</div>
</div>
提前谢谢你,
答案 0 :(得分: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 class="foo">');
如果第一个和最后一个之间有多个div,您可以这样做:
$('div:first').replaceWith('<div class="foo">');
$('div.foo').nextAll('div').appendTo('div.foo');
$('div.foo :last').remove();