Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch positions of 2 divs with jQuery

Tags:

html

jquery

I'm wondering if it's posible to switch positions of two divs with jQuery.

I have two div like this

<div class="div1">STUFF ONE</div> <div class="div2">STUFF TWO</div> 

so if div2 has content (or contains more than just white spaces) it switches the order of div1 and div2

so this:

<div class="div1">STUFF ONE</div> <div class="div2">STUFF TWO</div> 

would become this:

<div class="div2">STUFF TWO</div> <div class="div1">STUFF ONE</div> 

But if it was this:

<div class="div1">STUFF ONE</div> <div class="div2"></div> 

or this:

<div class="div1">STUFF ONE</div> <div class="div2">    </div> 

it wouldn't do anything.

Also... if posible, if switched I would like to add a class to div1.

Any help with this will be very much appreciated.

UPDATE:

I forgot to add that I have to run this across multipul instanses on the same page.

Each instance is formated like this:

<div class="view-container">    <div class="view-content">     <div class="views-row">      <div class="div1">STUFF ONE</div>      <div class="div2">STUFF TWO</div>    </div>    <div class="views-row">      <div class="div1">STUFF ONE</div>      <div class="div2">STUFF TWO</div>    </div>   </div> </div> 
like image 671
Cybercampbell Avatar asked Jan 27 '12 07:01

Cybercampbell


2 Answers

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'));     } }); 
like image 83
Rusty Fausak Avatar answered Sep 17 '22 12:09

Rusty Fausak


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"); } 
like image 43
Vigrond Avatar answered Sep 17 '22 12:09

Vigrond