0

Example HTML :

<h2 class="x1">1</h2>
<h2 class="x2">2</h2>
<h2 class="x3">3</h2>
<h2 class="x4">4</h2>
<h2 class="x5">5</h2>

I want to switch like...

1
2 <---
3     |
4     |
5 <---

So I do like this

$('.x2').insertBefore('.x5');
$('.x5').insertBefore('.x2');

So I get result like this

1
3
4
5 <--- 
2 <--- 

How can I get result like... ?

1
5 <---
3     |
4     |
2 <---

Playground : http://jsfiddle.net/l2aelba/aHwSJ/

PS : If possible I dont want to do like

$('.x2').insertBefore('.x5');
$('.x5').insertBefore('.x3');

I need to select element only 2 elements (NOT ANOTHER)

l2aelba
  • 21,591
  • 22
  • 102
  • 138

5 Answers5

2

You want to insert .x5 before the next sibling of .x2, not before .x2 itself.

var next = $('.x2').next();
$('.x2').insertBefore('.x5');
$('.x5').insertBefore(next);

This does only work if .x2 is not the last sibling though.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Try

var pos = $('.x2').index();
$('.x2').insertBefore('.x5');
$('.x5').insertBefore($('h2').eq(pos));

Demo: Fiddle

The previous may not work if the order of elements changes, try this

var el1 = $('.x4'), el2 = $('.x1'), el1prev = el1.prev();
el1.insertBefore(el2);
if(el1prev.length){
    el2.insertAfter(el1prev);
} else {
    el2.insertAfter($('h2').eq(0));
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Starting from this good solution https://stackoverflow.com/a/698386/975520 you can made up your own jQuery function to handle the switch capabilities.

Here is the code:

jQuery.fn.swapWith = function(to) {
    return this.each(function() {
        var copy_to = $(to).clone(true);
        var copy_from = $(this).clone(true);
        $(to).replaceWith(copy_from);
        $(this).replaceWith(copy_to);
    });
};

And use it like:

$(document).ready(function () {
    $('.x5').swapWith('.x2');
});

I appreciate this solution because using the deep clone method all bound events are preserved.

Here is a working fiddle: http://jsfiddle.net/IrvinDominin/axvp9/

Community
  • 1
  • 1
Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
  • I appreciate that you linked to the original question, but since this is an exact copy, you rather should have voted to close the question as duplicate. – Felix Kling Jun 05 '13 at 08:15
0

use temporary div:

var x2 = $('.x2');
var x5 = $('.x5');
var div =$('<div>');

x2.replaceWith(div);
x5.replaceWith(x2);
div.replaceWith(x5);
Yukulélé
  • 15,644
  • 10
  • 70
  • 94
-1

Try this : http://jsfiddle.net/aHwSJ/1/

HTML:

<h2 class="x1">1</h2> 
<h2 class="x2">2</h2> 
<h2 class="x3">3</h2> 
<h2 class="x4">4</h2> 
<h2 class="x5">5</h2>

code:

var pos = $(".x2").next();
$('.x2').insertBefore('.x5');
$('.x5').insertBefore(pos);
Mathi
  • 742
  • 1
  • 10
  • 15