52

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?

2
  • 1
    @rahul - they're invalid in HTML4, be clear about that given the changes lately ;) Commented Dec 13, 2010 at 11:27
  • 2
    @rahul: ID is just only for example :), the real script of course not that. Commented Dec 13, 2010 at 12:41

3 Answers 3

91

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for understand if ID just only for example, and also your code $("#2").insertBefore("#1"); is clearing my problem... thank you very much :)
8

Simply do:

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

2 Comments

why the $('#2') instead of just '#2' ?
@FranciscoCorralesMorales Because, the before method expects, as parameter, an HTML string or a DOM element or an array of elements or a jQuery object. '#2' is not any of those.
3

Ever thought about using jQuery UI Sortable ?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.