Question

How can I change this:

<div class="container">
  <div class="span-19">
    <div id="content">
       <!-- variable amount of content -->
         <form class="move-me">
        <!-- form -->
         </form>
    </div>
  </div>
</div>

Into this:

<form class="move-me">
  <div class="container">
    <div class="span-19">
      <div id="content">
        <!-- variable amount of content -->
        <!-- form data -->
      </div>
    </div>
  </div>
</form>

Using jQuery? Note, I specifically want to move only the <form> start and end tags, not the children elements of that form. Preferably I want some jQuery.fn so that I can do this:

$('.move-me').changeNesting('.container');

Thanks in advance!

Was it helpful?

Solution

Use unwrap and wrap:

var toMove = $('.move-me'​);
toMove.​​​​​​children().unwrap()​;
$('.container'​).wrap(toMove);​

UPDATE: please note that the code above won't work if the form has nested raw text. You could wrap the form's children with another tag for it to work (also using end as pointed out by Yoshi in the comments):

$('.container').wrap(
  $('.move-me').wrapInner('<div class="nostyle"/>').children().unwrap().end()
);​​​​

OTHER TIPS

Using .wrap() and .detach() , like this:

$('.container').wrap( $('form.move-me').detach() );
$('.move-me').replaceWith(function() {
    return $('*', this);
});
$('.container').wrap('<form class="move-me" />');​

demo http://jsfiddle.net/KX63Z/

var $form=$('form.move-me')
$form.replaceWith($form.html()));
$('.container').wrap('<form class="move-me">');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top