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

Consider the following:

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"' />') didn't seem to work.

Answers


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.


try this

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

it would actually wrap the div before the lot replace the target div but will achieve the same result.

See here

http://jsfiddle.net/WgW6Y/


Need Your Help

Using python to build web applications

python cgi

This is a follow-up to two questions I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what language(s) to us...

Xcode 6.1.1 Storyboard changes layout when I re-open the project

ios8 xcode6 uistoryboard xcode-storyboard

When I open xcode and create layout everything looks pretty much like it should (meaning that the storyboard view controller looks pretty much like the preview)