My HTML structure is like this:
我的HTML结构是这样的:
<div id="parent">
<div id="1">Some content</div>
<div id="2">Some content</div>
</div>
I want to move the element id="2"
to place before id="1"
so its will be like this:
我想将元素id =“2”移到id =“1”之前,所以它将是这样的:
<div id="parent">
<div id="2">Some content</div>
<div id="1">Some content</div>
</div>
How do I do something like that in jQuery?
我如何在jQuery中做这样的事情?
3 个解决方案
#1
66
You can use .insertBefore()
, like this:
您可以使用.insertBefore(),如下所示:
$("#2").insertBefore("#1");
Or, .prependTo()
, like this:
或者,.prependTo(),如下所示:
$("#2").prependTo("#parent");
...or the reverse using #1
and .insertAfter()
and .appendTo()
...or several other ways actually, it just depends what you're actually after, the above 2 methods should be about the shortest possible though, given 2 IDs.
...或反过来使用#1和.insertAfter()和.appendTo()...或其他几种方式实际上,它只取决于你实际使用的内容,上述两种方法应该尽可能短,给出2个ID。
I'm assuming this is just an example, remember to use IDs that don't start with a number in an actual HTML4 page, they're invalid and cause several issues.
我假设这只是一个示例,请记住使用不以实际HTML4页面中的数字开头的ID,它们无效并导致多个问题。
#2
7
Simply do:
简单地说:
$('#1').before($('#2'));
#1
66
You can use .insertBefore()
, like this:
您可以使用.insertBefore(),如下所示:
$("#2").insertBefore("#1");
Or, .prependTo()
, like this:
或者,.prependTo(),如下所示:
$("#2").prependTo("#parent");
...or the reverse using #1
and .insertAfter()
and .appendTo()
...or several other ways actually, it just depends what you're actually after, the above 2 methods should be about the shortest possible though, given 2 IDs.
...或反过来使用#1和.insertAfter()和.appendTo()...或其他几种方式实际上,它只取决于你实际使用的内容,上述两种方法应该尽可能短,给出2个ID。
I'm assuming this is just an example, remember to use IDs that don't start with a number in an actual HTML4 page, they're invalid and cause several issues.
我假设这只是一个示例,请记住使用不以实际HTML4页面中的数字开头的ID,它们无效并导致多个问题。
#2
7
Simply do:
简单地说:
$('#1').before($('#2'));