Javascript 完全剪切并粘贴元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7186644/
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-24 01:15:21  来源:igfitidea点击:

cut completely and paste an element

javascriptjquery

提问by mrdaliri

Can I cut (completely, with all styles and attributes) an element from a location and paste it in another location (like body) with jQuery?

我可以body使用 jQuery从一个位置剪切(完全,具有所有样式和属性)一个元素并将其粘贴到另一个位置(如)吗?

Also, I want to place a string (or tag) in the old location, because I want to change its place to old location at the end of the script.

另外,我想在旧位置放置一个字符串(或标记),因为我想在脚本末尾将其位置更改为旧位置。

Can I? How?

我可以吗?如何?

Thank you.

谢谢你。

回答by Frédéric Hamidi

appendTo()will automatically move the matched elements from their current location to the specified container, which seems to be what you want.

appendTo()会自动将匹配的元素从其当前位置移动到指定的容器,这似乎是您想要的。

You can use after()to insert new content before moving the element:

您可以使用after()在移动元素之前插入新内容:

$("#yourElement").after("<p>Element was there</p>").appendTo("body");

回答by kamal pal

.detach()is more appropriate for this task, as @lvan suggested.

.detach()正如@lvan 建议的那样,更适合此任务。

jQuery(jQuery("#yourElement").detach()).appendTo("body");

回答by Jayantha Lal Sirisena

you can do it by clone first copy it to another location

您可以通过先克隆将其复制到另一个位置来完成

$('#yourElement').clone().appendTo('#anotherDiv');

then remove old one,

然后删除旧的,

 $('#parentOfOldElement #yourElement').remove();

or you can replace it to get it later

或者您可以更换它以稍后获取

  $('#parentOfOldElement #yourElement').replaceWith('<div id="toReplaceAgain">/div>');