replaceWith Automatically Closes the Tag

十年热恋 提交于 2019-12-10 18:00:17

问题


I have 3 divs and I want to replace the first div with an opening tag of another div and the third with the closing tag. This is what I meant:

<div>1</div>
<div>2</div>
<div>3</div>

When I tried to replace (using replaceWith()) the first div with <div class="foo"> and the third with </div>, jQuery somewhat misinterpret it as:

<div class="foo"></div>
<div>2</div>
</div>

While what I actually want is:

<div class="foo">
 <div>2</div>
</div>

Thank you in advance,


回答1:


You should work with whole elements rather than pieces of HTML code. Another way to think about it is:

// 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">');

If there are multiple divs between the first and the last, you may do this:

$('div:first').replaceWith('<div class="foo">');
$('div.foo').nextAll('div').appendTo('div.foo');
$('div.foo :last').remove();

See demo: http://jsfiddle.net/TBMHt/



来源:https://stackoverflow.com/questions/4679142/replacewith-automatically-closes-the-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!