ReplaceWith automatically closes the tag

I have 3 divs, and I want to replace the first div with the open tag of another div, and the third with the closing tag. That's 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 misinterpreted it as:

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

While I really want:

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

Thanks in advance,

+3
source share
1 answer

You should work with all elements, not snippets of HTML code. Another way to think about it:

// 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 last, you can 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/

+2
source

Source: https://habr.com/ru/post/1785164/


All Articles