Posts Tagged ‘Reparenting’
Reparenting child nodes
In a previous post, I suggested a quick and simple way of moving an element from one parent to another, in this post, I will present you with a reusable function that will move all child nodes from one parent element to another:
function moveChildren(srcEl, destEl) {
while (srcEl.hasChildNodes()) {
var child = srcEl.childNodes[0];
destEl.appendChild(child);
}
}
Here is an example HTML page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">
<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" >
<head>
<title>Reparenting Example</title>
<style type="text/css">
div { border: solid 1px #000; padding: 10px; }
span { border: solid 1px #f00; padding: 2px; }
#Box1 { background-color: #ccc; }
#Box2 { background-color: #ffc; }
#Box3 { background-color: #ccf; }
</style>
</head>
<body>
<div id="Box1">
<span>Box1 content</span>
<div id="Box2">
<span>Box2 content</span>
<div id="Box3">
<span>Box3 content</span>
<span>More Box3 content</span>
</div>
<span>More Box2 content</span>
</div>
<span>More Box1 content</span>
</div>
<input type="button" value="Reparent" onclick="reparent()" />
<script type="text/javascript">
var box1 = document.getElementById("Box1");
var box2 = document.getElementById("Box2");
var box3 = document.getElementById("Box3");
function reparent() {
moveChildren(box2, box1);
moveChildren(box3, box1);
}
function moveChildren(srcEl, destEl) {
while (srcEl.hasChildNodes()) {
var child = srcEl.childNodes[0];
destEl.appendChild(child);
}
}
</script>
</body>
</html>
In this example, when you click the [Reparent] button, all child nodes of Box2 and Box3 will be moved to Box1.
References