最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to swap position of HTML tags? - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 11

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/

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.

发布评论

评论列表(0)

  1. 暂无评论