If I have the HTML:
<div id="divOne">Hello</div> <div id="divTwo">World</div>
Is it possible with CSS/JS/jQuery to swap it around so the contents of divTwo
appears in the position of divOne
and vice-versa ? I'm just looking to change the position of each div, so I don't want any solution that involves setting/swapping the HTML of each.
The idea is to let a user customise the order content appears on the page. Is what I'm trying to do a good way of going about that, or is there a better way of achieving it ?
If I have the HTML:
<div id="divOne">Hello</div> <div id="divTwo">World</div>
Is it possible with CSS/JS/jQuery to swap it around so the contents of divTwo
appears in the position of divOne
and vice-versa ? I'm just looking to change the position of each div, so I don't want any solution that involves setting/swapping the HTML of each.
The idea is to let a user customise the order content appears on the page. Is what I'm trying to do a good way of going about that, or is there a better way of achieving it ?
Share Improve this question asked Dec 10, 2010 at 6:13 Michael LowMichael Low 24.5k17 gold badges84 silver badges119 bronze badges3 Answers
Reset to default 11You'll be relieved to know it's not hard at all using jQuery.
$("#divOne").before($("#divTwo"));
Edit: If you're talking about implementing drag-and-drop functionality for ordering the divs, take a look at jQuery UI's sortable plugin... http://jqueryui.com/demos/sortable/
http://snipplr.com/view/50142/swap-child-nodes/ has the code to swap 2 elements with each other.
I have also modified the same code so that it also preserves event listeners (addEventListener
) in the elements that are being swapped and their child nodes.
function swapNodes(node1, node2) {
node2_copy = node2.cloneNode(true);
node1.parentNode.insertBefore(node2_copy, node1);
node2.parentNode.insertBefore(node1, node2);
node2.parentNode.replaceChild(node2, node2_copy);
}
Perhaps by using floats.
#divOne {
float: right;
}
#divTwo {
float: left;
}
YMMV.