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');
}));
$('#container > div').each( function(event) {
$(this).css('z-index', $(this).attr('order'));
});
Try to look here. Could be useful for understanding fundamental principles. http://james.padolsey.com/javascript/sorting-elements-with-jquery/
I think u want this :DEMO
$('#container > div').sortElements(function(a, b){
return parseInt($(a).attr('order')) > parseInt($(b).attr('order')) ? 1 : -1;
});
Here is how to sort divs by attribute "tag" as a single word. JSFiddle has code to check for multiple words, etc. Posting because couldn't find solution when I was looking for it.
<div id="tag_sections">
<!-- populated with sorted divs -->
</div>
<div id="all_tags">
<div data-tag="blue">8</div>
<div>1</div>
<div data-tag="tag">2</div>
<div data-tag="red">3</div>
<div data-tag="blue">4</div>
<div>5</div>
<div data-tag="red">6</div>
<div data-tag="blue">7</div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
// sort all by title tag
var allTags = [];
$('#all_tags div').each(function() {
theTag = $(this).attr('data-tag');
if (!theTag) { theTag = 'ungrouped'; }
if (!$('#'+theTag).length) {
allTags.push(theTag);
$('#tag_sections').append('<div id="'+theTag+'"><h3>'+theTag+'</h3></div>');
}
if ($.inArray(theTag, allTags) > -1) {
$('#tag_sections #'+theTag).append($(this));
}
});
</script>
http://jsfiddle.net/zyEwF/269/
Demo of sorting by attribute value that is not a number and creates new div to add those sorted elements into.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.