23

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.

Rob W
  • 341,306
  • 83
  • 791
  • 678
iroel
  • 1,760
  • 1
  • 18
  • 27

2 Answers2

38
document.getElementById('target').appendChild(  document.getElementById('to_be_moved') )
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • What about "to_be_moved"? Is it still in its original place? – iroel Jul 28 '10 at 21:23
  • 3
    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 omuraliev Jul 28 '10 at 21:29
  • 5
    "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..." https://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. – captain puget Feb 02 '20 at 05: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)
Steven
  • 17,796
  • 13
  • 66
  • 118