0

So this is my javascript for sorting a lists (alphabetically) with links:

function compareText(a1, a2) {
var t1 = a1.innerText, t2 = a2.innerText;
return t1 > t2 ? 1 : (t1 < t2 ? -1 : 0);
}

function sortUnorderedList(ul, sortDescending) {
 if(typeof ul == "string") {
 ul = document.getElementById(ul);
 }  

var lis = ul.getElementsByTagName("LI");
var vals = [];

 for(var i = 0, l = lis.length; i < l; i++) {
vals.push(lis[i]);
 }

vals.sort(compareText);

if(sortDescending) {
  vals.reverse();
}

ul.innerHTML = '';
for(var i = 0, l = vals.length; i < l; i++) {
ul.appendChild(vals[i]);
   }
  }

 <div id="test"> <a href="#">Sort List</a>

  </div>
 <ul id="list">
  <li><a href="www.tumblr.com/post/9080">apple</a></li>
  <li><a href="www.tumblr.com/post/2378">pie</a></li>
  <li><a href="www.tumblr.com/post/5627">banana</a></li>

  </ul>

now this script works perfectly in safari, but in firefox for instance, it doesn't work.. how to get this work in all browsers?

M'''
  • 51
  • 2
  • 11
  • 2
    possible duplicate of ['innerText' works in IE, but not in Firefox](http://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox) – Jeremy J Starcher Aug 14 '13 at 07:58

2 Answers2

2

You have to use textContent instead of innerText. innerText will return undefined in Firefox.

w3.org textContent

Demo Try before buy

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
0

The problem you have in Firefox is probably due to the fact that the Document Object Model (DOM) is not ready and available when the JavaScript is executed. Different browsers handle things differently and when scripts are executed are one of those things.

What you need to do is to:

  1. Wrap your code in a function
  2. Execute that function when the page (DOM) is ready

You can use this to detect when the page is loaded:

var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        init(); // This is the function that would contain your code.
        clearInterval(readyStateCheckInterval);
    }
}, 10);
Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79