Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 414
GusDeCooL Avatar asked Dec 13 '10 11:12

GusDeCooL


People also ask

How do I move a div to another div?

Answer: Use the jQuery . appendTo() Method You can use the jQuery . appendTo() method to move an element into another element.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


2 Answers

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.

like image 65
Nick Craver Avatar answered Oct 05 '22 15:10

Nick Craver


Simply do:

$('#1').before($('#2')); 
like image 40
David Tang Avatar answered Oct 05 '22 17:10

David Tang