[jQuery] Sorting links alphabetically with jQuery
Hi, I'm having some problems figuring out how to sort links
alphabetically based on their text content and hold the reference to
the link. I can do it sans jQuery, but I'd really like to be able to
use jQuery to do it.
This is what I want to do with jQuery:
<div id="test">
<a href="http://yahoo.com">Yahoo</a>
<a href="http://google.com">Google</a>
<a href="http://aol.com">Aol</a>
</div>
function sortText(a, b) {
if ( a.text < b.text ) return -1;
else if ( a.text > b.text ) return 1;
return 0;
}
var meh=[];
var getT = document.getElementById('test');
var getas = getT.getElementsByTagName( 'a' );
for(var i=0;i < getas.length; i++){
meh[i]={ text: getas[ i ].textContent, el: getas[ i ] };
}
var sortedLinks = meh.sort( sortText );
getT.innerHTML = '';
for(var l=0;l < sortedLinks.length; l++){
getT.appendChild(sortedLinks[l].el);
}
This is my jQuery attempt:
function sortText(a, b) {
if ( a.text < b.text ) return -1;
else if ( a.text > b.text ) return 1;
return 0;
}
var meh=[];
$('#test a').each(function(){
meh[i] = { text: $(this).text(), el: $(this) };
});
var sortedLinks = meh.sort( sortText );
$(sortedLinks).each(function(l){
$('#test).append([l].el);
});
...but that doesn't seem to work.
I've also tried using $.map, but I couldn't figure it out.