Rick
Rick

Reputation: 17013

JQuery (Javascript) / CSS, way to rearrange order of elements within DIV without using positioning?

I'm a bit unsure of how to do this. I have a main panel where I want to display a DIV in that based on an action. I have the DIVS laid out like this in the html:

<div id="container">
   <div id="1"></div>
   <div id="2"></div>
</div>

Rather than messing around with positioning, I want to make it so that when something happens I can just put div id=2 above div id=1, as simply as possible. Any advice is appreciated.

Upvotes: 2

Views: 2551

Answers (3)

lincolnk
lincolnk

Reputation: 11238

remove the second element and reinsert it before the first element.

javascript:

var d1 = document.getElementById('1');
var d2 = document.getElementById('2');

d2.parentNode.removeChild(d2);
d1.parentNode.insertBefore(d2, d1);
​

Upvotes: 0

stecb
stecb

Reputation: 14746

You simply do this absolute positioning the divs. If something happens, just set z-index of the elements. For example (using simple JS):

var d1 = document.getElementById('1');
var d2 = document.getElementById('2');

d1.style.zIndex = 1;
d2.style.zIndex = 2;

If you want to update them, just reset the zIndex ;)

Upvotes: 1

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

In the example you are showing you can simply use the append, and prepend jquery methods.

For example, div#1 then div#2

$('#container').append('#1').append('#2');

Reorder, div#2 then div#1

$('#container #2').remove().prependTo('#container');

There are many ways you could write this. Just remember prepend places an element at the beginning (before the first element) of the container, while append places the element after the last element.

Upvotes: 6

Related Questions