Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move the beginning and end tags of a HTML DOM element?

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!

like image 223
Adam Avatar asked Nov 03 '12 23:11

Adam


People also ask

How do I grab an element from a DOM?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.

How do you move an element from one element to another?

All you have to do is select the element(s) you want to move, then call an “adding” method such as append() , appendTo() or prepend() to add the selected elements to another parent element.

What are DOM elements in HTML?

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.


2 Answers

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()
);​​​​
like image 137
Jordão Avatar answered Oct 20 '22 01:10

Jordão


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

$('.container').wrap( $('form.move-me').detach() );
like image 27
Nelson Avatar answered Oct 20 '22 00:10

Nelson