0

I was working on filtering a table alphabetically and ran into a problem. I don't understand x.innerHTML > y.innerHTML concept in this code:

 table = document.getElementById('myTable');
 rows = table.getElementsByTagName('tr');
 x = rows[1].getElementsByTagName('td')[0];
 y = rows[2].getElementsByTagName('td')[0];
 //check if the two rows should switch place:
 console.log(x.innerHTML.length, y.innerHTML.length);
 console.log(x.innerHTML > y.innerHTML);

How does it work?

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
Benas Lengvinas
  • 414
  • 1
  • 4
  • 16
  • Possible duplicate of [Why is one string greater than the other when comparing strings in JavaScript?](https://stackoverflow.com/questions/7087811/why-is-one-string-greater-than-the-other-when-comparing-strings-in-javascript) – jmargolisvt Aug 26 '17 at 15:35
  • FYI, you don't need `getElementsByTagName` there. `table.rows[1].cells[0]` works just as well. – spanky Aug 26 '17 at 15:42

2 Answers2

5

innerHTML returns a string, so you just compare two strings:

"albert" < "boby" // true

From ECMAScript Language Specification

The comparison of Strings uses a simple lexicographic ordering on sequences of code unit values. There is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined in the Unicode specification. Therefore String values that are canonically equal according to the Unicode standard could test as unequal. In effect this algorithm assumes that both Strings are already in normalised form. Also, note that for strings containing supplementary characters, lexicographic ordering on sequences of UTF-16 code unit values differs from that on sequences of code point values.

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
1

x.innerHTML and y.innerHTML are strings, therefore if you want their value as a number, you need to surround them with Number() as follows:

Number(x.innerHTML)>Number(y.innerHTML)

Otherwise, you are comparing two strings with an inequality, which the computer takes a different way, as shown above in another answer.

Assafi Cohen-Arazi
  • 837
  • 10
  • 30