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) { if(aType == '3') { var at = $(a).find(".l").first().html() + $(a).find(".f").first().html(); at = at.toLowerCase(); var bt = $(b).find(".l").first().html() + $(b).find(".f").first().html(); bt = bt.toLowerCase(); if(at == bt) return 0; return at<bt ? -1 : 1; } else { 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"><span class="f">Zach</span> <span class="l">Bastion</span></span> <li class="contact"><span class="f">Joe</span> <span class="l">Smith</span></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"><span class="f">Sally</span> <span class="l">Johnson</a></li> <li class="account">Spacely Sprockets</li> <li class="account">Cogs 'R Us</li> <li class="account">Widgets Widgets Widgets</li> <li class="contact"><span class="f">Tom</span> <span class="l">Apple</span></li> </ul> <input type="button" onclick="$('#test li').customSort();" value="Sort">
li.contact { color: green } li.account { color: blue } li.market {color: red}