How to move HTML element

给你一囗甜甜゛ 提交于 2019-12-03 07:20:59

问题


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:


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



回答2:


$("target").insert($("to_be_moved").remove());

Or, for a more readable way...

var moveIt = $("to_be_moved").remove();
$("target").insert(moveIt);



回答3:


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)


来源:https://stackoverflow.com/questions/3357575/how-to-move-html-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!