Skip to content Skip to sidebar Skip to footer

Flip Div Element

01
02
03
1

HTML:

<divid="bar"><divclass="h2">1</div><divclass="h2">8</div><divclass="h2">2</div></div>

JS:

$(document).ready(function () {
  $('#bar').find('.h2').each(function(){
    var currentItem = $(this),
        nextItem = $(this).next('.h2'),
        currentItemValue = parseInt(currentItem.text()),
        nextItemValue = parseInt(nextItem.text());

    if(currentItemValue > nextItemValue) {
        currentItem.before(nextItem);
    }

  });
});

fiddle

This is a more dynamic approach to swap elements depending on it's innerHtml. Maybe it's what you want

Solution 2:

You can achieve the desired result with the following jQuery ... see jsFiddle Demo

HTML

<divid="bar"><divid="h2"> 01 </div><divid="h2"> 02 </div><divid="h2"> 03 </div><divclass="h1"> 1
    <divid="a1"> 8 </div></div><divid="h2"> 2 </div></div>

JS

var last= $('#bar > div:last-child').clone(),
    inner = $('#a1').clone();

$('#bar > div:last').remove();
$('#bar').append(inner);

$('.h1').children().remove();
$('.h1').append(last);

Solution 3:

JQuery

functionreverseChild($parent, index,$replaceObj) {
    var childItem = $parent.children().eq(index-1);
    var replaceObjIndex=$replaceObj.index()+1;
    $replaceObj.insertAfter(childItem);
    insertAtIndex("bar",replaceObjIndex,childItem);
};
$(document).ready(function () {
    reverseChild($('#bar .h1'), 1,$("#bar").children('div:last'));
});
functioninsertAtIndex(objID,i,$insertItem) {
    if(i === 0) {
     $("#"+objID).prepend($insertItem);        
     return;
    }
    $("#"+objID+" > div:nth-child(" + (i-1) + ")").after($insertItem);
}

DEMO

Post a Comment for "Flip Div Element"