Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder DIV's based on element attributes

I'm not sure how to go about doing this. Let's say I have the following HTML code:

<div id="container">
  <div class="item" order="5"></div>
  <div class="item" order="3"></div>
  <div class="item" order="4"></div>
  <div class="item" order="1"></div>
  <div class="item" order="2"></div>
</div>

Using jQuery, how could I order these divs based on the attribute "order"? By reorder, I mean I would like the dom to update the order of the divs based on the attribute "order". This would naturally adjust the z-index of the divs as well. I know that setting the z-index based on the attribute order will give me the correct display in the browser window, but it won't manipulate the dom order.

I assume I would loop through #container and get the child and its order like so:

$('#container > div').each( function(event) {
   var itemOrder = $(this).attr('order');
});

...but I'm at a loss on how to manipulate the order. Any help would be greatly appreciated.

like image 767
Andrew Avatar asked Mar 03 '26 02:03

Andrew


2 Answers

You can do this :

$('#container').append($('#container .item').sort(function(a,b){
   return a.getAttribute('order')-b.getAttribute('order');
}));

Demonstration

like image 199
Denys Séguret Avatar answered Mar 05 '26 14:03

Denys Séguret


$('#container > div').each( function(event) {
    $(this).css('z-index', $(this).attr('order'));
});
like image 26
Eric Hotinger Avatar answered Mar 05 '26 14:03

Eric Hotinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!