Update Panel .NET

Exploring Microsoft ASP.NET AJAX and jQuery

Archive for May 2008

Moving an element within the DOM using JavaScript

with one comment

The easiest way to move an element from one parent to another (re-parenting) is to use:

newParent.appendChild(element);

The element will be “detached” from its original parent and “attached” to its new parent.

Consider this block of HTML:

<h3>Old position</h3>
<div id="oldParent">
<ul id="colorList">
	<li>Red</li>
	<li>Amber</li>
	<li>Green</li>
</ul>
</div>
<h3>New position</h3>
<div id="newParent"></div>

This script will move the complete list structure “colorList” from “oldParent” to “newParent” and back again:

var element = document.getElementById("colorList");
var oldParent = document.getElementById("oldParent");
var newParent = document.getElementById("newParent");
// Move to new parent.
newParent.appendChild(element);
// Back to old parent.
oldParent.appendChild(element);

Works on all W3C DOM Level 1 compliant browsers.

Written by tzkuei

May 21, 2008 at 12:00 am

Posted in DOM, JavaScript

Tagged with ,