Search code examples
javascriptprototypejs

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


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

Inside the div is a form with ids and dependent Javascript code with event observers. I don't want this to break just because I have moved a block in the DOM. A 'this innerHTML = that innerHTML' solution is not what I am looking for. I will also be needing to do this when the DOM is loaded.

I want to go from this:

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

to this:

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

...when the document loads with nothing jumping about.


Solution

  • You can add this at the very end of the BODY tag:

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

    MacGuffin will be moved automatically from one to the other.
    And there won't be any flickering.