24

How to rearrange elements using jQuery ?

Orginal Code :

<p id="paragraph1">1</p>
<p id="paragraph2">2</p>
<p id="paragraph3">3</p>
<p id="paragraph4">4</p>
<p id="paragraph5">5</p>

After Rearrange (put p3 in p2's place)

<p id="paragraph1">1</p>
<p id="paragraph3">3</p>
<p id="paragraph2">2</p>
<p id="paragraph4">4</p>
<p id="paragraph5">5</p>
1
  • 1
    how are you wanting to rearrange them? when someone clicks a button? when someone drags the element around the screen? more details please. Commented Feb 5, 2011 at 21:51

1 Answer 1

44

You can use .insertBefore():

$("#paragraph3").insertBefore("#paragraph2");

Slightly more elaborate example (clicking on a paragraph moves it up):

$("p").click(function() {
   $(this).insertBefore($(this).prev()); 
});

You can test both examples here.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.