Skip to content Skip to sidebar Skip to footer

Sorting Of Div Data Using Jquery Or Javascript

I'm trying to sort some DIVS in different ways and I'm quite lost. I've been trying some stuff but I don't see how to get it to work. I have div data in following format. I have a

Solution 1:

An example to sort by price:

$('#content div.price').map(function () {
  // map sort-value and relevant dom-element for easier handlingreturn {val: parseFloat($(this).text(), 10), el: this.parentNode};
}).sort(function (a, b) {
  // a simple asc-sortreturn a.val - b.val;
}).map(function () {
  // reduce the list to the actual dom-elementreturnthis.el;
}).appendTo('#content'); // < inject into parent node

demo: http://jsfiddle.net/QmVsD/1/


a few notes:

  • the first map isn't really needed, but it makes the sorting callback much simpler.
  • you would need to supply different compare-callbacs for different data-types (e.g. dates, strings)

Solution 2:

What you've got there is actually a TABLE, so use a table and one of the existing table sorters.

There is nothing wring with using <table> when you have tabular data, and that's what you've got.

Solution 3:

The generated HTML is part of the presentation, while the sorting operation is part of the data model. You should separate these two concepts in your code.

In your case, store the data in arrays (data model). When you want to display the data to user only then lay it out in divs or table html. Do the sorting before you lay out the html. When the user chooses sorting option from the dropdown, empty the #contentContainer, sort the array of data, regenerate html of newly ordered data and insert it into #contentContainer.

Solution 4:

I just tested this and it worked fine for me. Youll just decide what you do with your array afterwards. :)

$(document).ready(function () {
var priceItems = $('.price');
var arr = newArray();
for (var i = 0; i < priceItems.length;i++) {
var tempInt = priceItems[i].innerHTML;
tempInt = parseInt(tempInt);
arr.push(tempInt);
}
arr.sort()  
});

All you now need, is use your array.

Post a Comment for "Sorting Of Div Data Using Jquery Or Javascript"