GusDeCooL
GusDeCooL

Reputation: 5758

How do I move an HTML element in jQuery?

My HTML structure is like this:

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

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

Upvotes: 52

Views: 71707

Answers (3)

Nick Craver
Nick Craver

Reputation: 630349

You can use .insertBefore(), like this:

$("#2").insertBefore("#1");

Or, .prependTo(), like this:

$("#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.

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.

Upvotes: 91

David Tang
David Tang

Reputation: 93664

Simply do:

$('#1').before($('#2'));

Upvotes: 8

Pit
Pit

Reputation: 1488

Ever thought about using jQuery UI Sortable ?

Upvotes: 3

Related Questions