如何将一个元素移动到另一个元素之前?如下例所示,我需要在 #parent
之前移动#child。在#parent 之前和之后已经存在一些div
,因此append
和prepend
将不起作用。之后和之前只取字符串。但是,parent 和 child 都有很多内容,所以我不能只将它们复制到 JavaScript 中。
<div id="container">
//many other existing divs
<div id="parent">
<div id="child"></div>
</div>
//many other existing divs
</div>
最佳答案
Insert every element in the set of matched elements before the target.
代码
$('#child').insertBefore('#parent')
$(function() {
$('#child').insertBefore('#parent')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div>many other existing divs
</div>
<div id="parent">
parent
<div id="child">child</div>
</div>
<div>many other existing divs
</div>
</div>
或者你也可以使用 .before()
Insert content, specified by the parameter, before each element in the set of matched elements.
$("#parent").before($('#child'));
$(function() {
$( "#parent").before($('#child'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div>many other existing divs
</div>
<div id="parent">
parent
<div id="child">child</div>
</div>
<div>many other existing divs
</div>
</div>
.before()
和.insertBefore()
方法执行相同的任务。主要区别在于语法——具体而言,在于内容和目标的位置。
关于javascript - 使用 ID 或 CLASSNAME 在另一个元素之前插入一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33472839/