Michael Low
Michael Low

Reputation: 24506

How to swap position of HTML tags?

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 ?

Upvotes: 7

Views: 7687

Answers (3)

user1651105
user1651105

Reputation: 1817

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);
}

Upvotes: 4

David Tang
David Tang

Reputation: 93714

You'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/

Upvotes: 11

alex
alex

Reputation: 490657

Perhaps by using floats.

#divOne {
   float: right;
}

#divTwo {
   float: left;
}

YMMV.

Upvotes: 2

Related Questions