How to move HTML element

2019-03-11 04:20发布

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.

3条回答
相关推荐>>
2楼-- · 2019-03-11 04:31

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)
查看更多
爷、活的狠高调
3楼-- · 2019-03-11 04:38
$("target").insert($("to_be_moved").remove());

Or, for a more readable way...

var moveIt = $("to_be_moved").remove();
$("target").insert(moveIt);
查看更多
时光不老,我们不散
4楼-- · 2019-03-11 04:51
document.getElementById('target').appendChild(  document.getElementById('to_be_moved') )
查看更多
登录 后发表回答