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.


Need Your Help

Transitioning from WPF to Silverlight

wpf silverlight

How hard is it to transition from WPF to Silverlight?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.