javascriptjqueryreplacewith

How can I replace a DOM node and wrap it after?


I have a div which I'm replacing with a textarea like:

var $targetDiv = $('#the-div');
var $newDiv = $('#the-new-div');

$targetDiv.replaceWith($newDiv);

Which would turn:

<div id="the-div"></div>

into:

<div id="the-new-div"></div>

How would I wrap <div id="the-new-div"></div> in a div called <div id="the-new-div-wrapper">?

So the outcome would become:

<div id="the-new-div-wrapper">
<div id="the-new-div">
</div>
</div>
$targetDiv.replaceWith($newDiv).wrap('<div id="the-new-div-wrapper"' />')

doesn't seem to work.


Solution

  • Do the wrapping first

    $targetDiv.wrap('<div id="the-new-div-wrapper" />').replaceWith($newDiv);
    

    Or make it in two lines:

    $targetDiv.replaceWith($newDiv);
    $newDiv.wrap('<div id="the-new-div-wrapper" />');
    

    Fiddle

    There's also a typo in your code: $targetDiv.replaceWith($newDiv).wrap('<div id="the-new-div-wrapper"' />') There is an additional apostrophe, which shouldn't be there.