jQuery.fn.customSort = function() { this.sort(function (a, b) { // give weights to account/market/contact // from their associated classes var aType,bType; if($(a).hasClass('market')) { aType = 1; } else if($(a).hasClass('account')) { aType = 2; } else if($(a).hasClass('contact')) { aType = 3; } if($(b).hasClass('market')) { bType = 1; } else if($(b).hasClass('account')) { bType = 2; } else if($(b).hasClass('contact')) { bType = 3; } // if we're comparing 2 items of the same // type, go down and level and sort them by // their html if (aType == bType) { a = $(a).html().toLowerCase(); b = $(b).html().toLowerCase(); if(a == b) return 0; return a < b ? -1 : 1; } return aType < bType ? -1 : 1; }); // reorder the nodes in the DOM. this.each(function (i) { this.parentNode.appendChild(this); }); };
<h2>Sort by type, then name.</h2> <ul id="test"> <li class="contact">Smith, Joe</li> <li class="market">APAC</li> <li class="market">EMEA</li> <li class="market">CALA</li> <li class="account">Thingees and More</li> <li class="market">US</li> <li class="contact">Johnson,Sally</li> <li class="account">Spacely Sprockets</li> <li class="account">Cogs 'R Us</li> <li class="account">Widgets Widgets Widgets</li> <li class="contact">Apple, Fiona</li> </ul> <input type="button" onclick="$('#test li').customSort();" value="Sort">
li.contact { color: green } li.account { color: blue } li.market {color: red}