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.
You can do this :
$('#container').append($('#container .item').sort(function(a,b){
return a.getAttribute('order')-b.getAttribute('order');
}));
Demonstration
$('#container > div').each( function(event) {
$(this).css('z-index', $(this).attr('order'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With