How to move HTML element

45,989

Solution 1

document.getElementById('target').appendChild(  document.getElementById('to_be_moved') )

Solution 2

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)
Share:
45,989

Related videos on Youtube

iroel
Author by

iroel

Updated on July 09, 2022

Comments

  • iroel
    iroel almost 2 years

    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.

  • iroel
    iroel almost 14 years
    What about "to_be_moved"? Is it still in its original place?
  • meder omuraliev
    meder omuraliev almost 14 years
    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.
  • captain puget
    captain puget over 4 years
    "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.