0

This is interesting, sorting links by content, but how would you go about it using javascript?

Sorry, I meant: you have this:
http://stackoverflow.com'>Stack Overflow
http://www.google.com'>Google
and you want this:
""Google ""
""Stack Overflow ""
...the links having now been sorted into alphabetical order by link.

Community
  • 1
  • 1
Paulx
  • 35
  • 1
  • 6

3 Answers3

1

Not sure why this does not work :( (using some code from Most efficient way to convert an HTMLCollection to an Array)

function sortAsc(a, b) {
  if (a.innerHTML > b.innerHTML) return 1;
  if (a.innerHTML === b.innerHTML) return 0;
  if (a.innerHTML < b.innerHTML) return -1;
}

function sortDsc(a, b) {
  if (a.innerHTML > b.innerHTML) return -1;
  if (a.innerHTML === b.innerHTML) return 0;
  if (a.innerHTML < b.innerHTML) return 1;
}

function $A(iterable) {
  if (!iterable) return [];
  if ('toArray' in Object(iterable)) return iterable.toArray();
  var length = iterable.length || 0,
    results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}


function sortLinks(containerId, dir) {
  var linksCollection = document.getElementById(containerId).getElementsByTagName('a');
  var links = $A(linksCollection)
  document.getElementById(containerId).innerHTML = links.sort(dir === "a" ? sortAsc : sortDsc).join('');
  return false;
}
<div id="sort-this-div">
  <a href="http://something45yer.com">Content3</a>
  <a href="http://somethingeyerty.com">Content1</a>
  <a href="http://somethingfwegrw.com">Content2</a>
  <a href="http://somethingt43rwer.com">Content4</a>
</div>
<a href="#" onclick="return sortLinks('sort-this-div','a')">Ascending</a>
<a href="#" onclick="return sortLinks('sort-this-div','d')">Descending</a>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

I'm not sure what you're asking. YOu just want to sort an array?

["Stack Overflow", "Google"].sort()
brad
  • 31,987
  • 28
  • 102
  • 155
0

Once you have an array of links then an example would be

jQuery:

$('a').sort(function(a, b) { 
  a = a.text; b = b.text; 
  return a < b ? -1 : a > b ? 1 : 0; 
});

without:

Array().slice.call(document.getElementsByTagName('a')).sort(function(a, b) { 
  a = a.text; b = b.text; 
  return a < b ? -1 : a > b ? 1 : 0; 
});

Using jQuery or whatever to get an array of links

Then it sorts the text in between the a tags

James Kyburz
  • 13,775
  • 1
  • 32
  • 33
  • Thanks very much; this works.What I did was: `function orthis() { var j = []; t = document.getElementById('linkBox2').getElementsByTagName('a'); for (var i=0;i' + t[i].lastChild.nodeValue +'');} j.sort(function(a, b) { a = a.text; b = b.text; return a < b ? -1 : a > b ? 1 : 0; }); j.sort(); document.getElementById('linkBox2').innerHTML += '

    ' +j; }`

    – Paulx Apr 30 '11 at 00:08