开发者

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

开发者 https://www.devze.com 2023-03-12 05:58 出处:网络
In prototype or normal-but-cross-browser-compatible Javascript, how do I move the contents of a div to the contents of another div?

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&g开发者_开发百科t;Hello Worlds!</p>
    </div>
</div>

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


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.


Perhaps not a major point, but there is no Node.migrateChild() built-in Javascript interface method. If a fragment already has a parent elsewhere in the DOM (as div id='MacGuffin' does in example markup above), appendChild() quietly detaches the argument fragment from any current parent before reattaching under the new parent. In my mind migrateChild() would be a more semantically meaningful method name than appendChild(), less need for StackOverflow developer searches to allude to its more powerful abilities.


To move the contents of here into there, this works, as long as here encloses everything you want to move, like a <div>:

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

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


To move the contents of here into there, you're basically after:

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

Sadly, that doesn't work.

As with the other two answers, it looks like you have to resort to plain JavaScript with prototype only providing a shorthand for 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 stats on DocumentFragments: http://ejohn.org/blog/dom-documentfragments/)

0

精彩评论

暂无评论...
验证码 换一张
取 消