views:

34

answers:

3

How to move HTML element to another element. Note that, I don't mean moving element's position. Consider this HTML code:

<div id="target"></div>
<span id="to_be_moved"></span>

I want to move "to_be_moved" to "target" so "target" has child "to_be_moved" now. So the result should be like this:

<div id="target"><span id="to_be_moved"></span></div>

I've searched in google (especially using prototype framework) but all I've got is moving position, not as I want. Thanks before.

+1  A: 
document.getElementById('target').appendChild(  document.getElementById('to_be_moved') )
meder
What about "to_be_moved"? Is it still in its original place?
iroel
It shouldn't be. Try it?
meder
Huh? The element's parent will change, so it's "moved". The node isn't "removed" though because it's now elsewhere in the DOM tree.
meder
A: 

Assuming you're working with native DOM elements, the Javascript method .appendChild will suit your needs.

In native Javascript, document.getElementByID is probably your best bet in getting the DOM element, so...

var target = document.getElementById('target')
document.getElementById('to_be_moved').appendChild(target)
Steven Xu
+1  A: 
$("target").insert($("to_be_moved").remove());

Or, for a more readable way...

var moveIt = $("to_be_moved").remove();
$("target").insert(moveIt);
Josh Stodola
Thanks Josh. This is what I want.
iroel
@iroel You are welcome. Click the checkmark to "accept" this as the official answer.
Josh Stodola
I have a question. What about "to_be_moved" property, values etc? Is it still has the same as before the move (like clone native DOM method) ?
iroel
@iroel Yes, the [`remove` ](http://www.prototypejs.org/api/element/remove) method takes the element out of the DOM and returns it. It is not a clone, it is *the* element.
Josh Stodola
You don't even need to use `.remove()`. You can just insert at the new position.
Josh