jQuery: Sort div's according to content of different sub divs
- by rayne
I'm trying to create a somewhat complex sorting feature which neither uses divs nor lists. Unfortunately two hours of googling didn't help me.
Here is the basic setup of my HTML:
<div id="all_elements">
<!-- one element -->
<div class="element">
<div class="wrapper">
<a href="/" title="links">
<img src="/img/image.jpg" border="0" alt="image" class="image" /></a>
<div class="details">
<h3><a href="/" title="title">Name (Sort Argument 1)</a></h3>
<div class="title"><a href="/" title="title">Title (Sort Argument 2)</a></div>
<div class="year">2010 (Sort Argumentt 3)</div>
<div class="country">Great Britain (Sort Argument 4)</div>
</div><!-- details -->
</div><!-- wrapper -->
</div><!-- element -->
</div> <!--all_elements-->
The setup is a bit complex, but basically .element is the element that needs to be sorted alphabetically according to either the contents of h3, div.title, div.year or div.country. So the user will be able to view the contents of the site either sorted by name, by year, by country or by title.
I have this jQuery snippet from a website, but all my attempts on trying to tell it to use the contents of e.g. h3 to sort have failed. Right now it sorts pretty much randomly.
jQuery.fn.sort = function() {
return this.pushStack([].sort.apply(this, arguments), []);
};
function sortAscending(a, b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
};
function sortDescending(a, b) {
return a.innerHTML < b.innerHTML ? 1 : -1;
};
$(document).ready(function() {
$("#sort").toggle(
function() {
$('#all_elements .element').sort(sortDescending).appendTo('#all_elements');
$(this).text("Sort Asc");
},
function() {
$('#all_elements .element').sort(sortAscending).appendTo('#all_elements');
$(this).text("Sort Desc");
});
});
How can I customize the function to sort the contents of my h3 or divs?