25

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.

2 Answers 2

39
document.getElementById('target').appendChild(  document.getElementById('to_be_moved') )
3
  • What about "to_be_moved"? Is it still in its original place?
    – iroel
    Commented Jul 28, 2010 at 21:23
  • 4
    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. Commented Jul 28, 2010 at 21:29
  • 7
    "If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position..." developer.mozilla.org/en-US/docs/Web/API/Node/appendChild. Useful to know that the combination amounts to a move, and not a copy. It is not implicit in the naming. node.cloneNode() will...do what it says. Commented Feb 2, 2020 at 5:15
1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.