Javascript 如何移动 HTML 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3357575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:18:16  来源:igfitidea点击:

How to move HTML element

javascriptprototypejselementmove

提问by iroel

How to move HTML element to another element. Note that, I don't mean moving element's position. Consider this HTML code:

如何将 HTML 元素移动到另一个元素。请注意,我不是指移动元素的位置。考虑这个 HTML 代码:

<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:

我想将“to_be_moved”移动到“目标”,所以“目标”现在有孩子“to_be_moved”。所以结果应该是这样的:

<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.

我在谷歌搜索过(特别是使用原型框架),但我所得到的只是移动位置,而不是我想要的。之前谢谢。

回答by meder omuraliev

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

回答by Josh Stodola

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

Or, for a more readable way...

或者,为了更易读的方式......

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

回答by Steven

Assuming you're working with native DOM elements, the Javascript method .appendChildwill suit your needs.

假设您正在使用本机 DOM 元素,Javascript 方法.appendChild将满足您的需求。

In native Javascript, document.getElementByIDis probably your best bet in getting the DOM element, so...

在原生 Javascript 中,document.getElementByID可能是获取 DOM 元素的最佳选择,所以......

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