Moving a div from one div to another div using Prototype?

In a prototype or Javascript compatible standard, but cross-browser, how do I move the contents of a div to the contents of another div?

Inside the div there is a form with identifiers and dependent Javascript code with event observers. I don't want this to break because I moved the block to the DOM. A 'this is innerHTML = that innerHTML' solution is not what I'm looking for. I will also need to do this when the DOM boots up.

I want to go from this:

<div id='here'> <div id='MacGuffin'> <p>Hello Worlds!</p> </div> </div> <div id='there'> </div> 

:

 <div id='here'> </div> <div id='there'> <div id='MacGuffin'> <p>Hello Worlds!</p> </div> </div> 

... when the document loads without a jump.

+8
javascript prototypejs
source share
4 answers

You can add this to the very end of the BODY tag:

 <script> document.getElementById('there').appendChild( document.getElementById('MacGuffin') ); </script> 

MacGuffin will automatically move from one to another.
And there will be no flicker.

+33
source share

Perhaps not the main point, but there is no built-in JavaScript interface method Node.migrateChild (). If the fragment already has a parent elsewhere in the DOM (as div id = "MacGuffin" does the markup in the example above), appendChild () calmly separates the argument fragment from any current parent before re-binding to the new parent element. In my opinion, migrateChild () will be a more semantically meaningful method name than appendChild (), the less the need to search for developers StackOverflow refers to its more powerful features.

+2
source share

To move the contents of here to there , you basically after:

 $('there').insert($('here').childNodes); 

Unfortunately this does not work.

As with the other two answers, it looks like you need to resort to simple JavaScript with a prototype, providing only an abridged version of document.getElementById .

 var frag = document.createDocumentFragment(); for (var c = $('nav').firstChild, n; c; c = n) { n = c.nextSibling; frag.appendChild(c); } $('header').appendChild(frag); 

(See John Resign's blog for performance statistics in DocumentFragments: http://ejohn.org/blog/dom-documentfragments/ )

+1
source share

To move the contents of here to there , this works, while here covers everything you want to move, for example, <div> :

 $('there').insert($('here').descendants()[0]); 

descendants () returns an array, and the insert takes content, so use the first element.

+1
source share

All Articles