Switch positions of 2 divs with jQuery

I'll throw in my solution

$('.div2:parent').each(function () {
    $(this).insertBefore($(this).prev('.div1'));
});

Edit: Doesn't work for whitespace in div2. Here's an updated solution:

$('.div2').each(function () {
    if (!$(this).text().match(/^\s*$/)) {
        $(this).insertBefore($(this).prev('.div1'));
    }
});

Here's an example:

http://jsfiddle.net/52xQP/1/

First you want to clone the elements. Then, check a condition if div2 is empty. Then, do the swap:

div1 = $('#div1');
div2 = $('#div2');

tdiv1 = div1.clone();
tdiv2 = div2.clone();

if(!div2.is(':empty')){
    div1.replaceWith(tdiv2);
    div2.replaceWith(tdiv1);

    tdiv1.addClass("replaced");
}

if(div1First){
 var div2 = ($('.div2')).detach();
 ($('.div1')).append(div2);
}else{
 var div1 = ($('.div1')).detach();
 ($('.div2')).append(div1);
}

Fiddle to try it.

Tags:

Html

Jquery