why innerHTML does not return true when compared with same string value?

隐身守侯 提交于 2019-12-11 06:24:10

问题


I have two tables on my html page with exact same data but there may be few difference which need to be highlighted. I and using the below Javascript but seems innerHTML does not work as expected-

function CompareTables()
{
var table1 = document.getElementById("table1")
var table2 = document.getElementById("table2")



for(var i=1; i < table1.rows.length; i++)
{
    for(var j=1; j < table2.rows.length; j++){
        var tab1Val = table1.rows[i].cells[0].innerHTML;
        var tab2Val = table2.rows[j].cells[0].innerHTML;
        alert(tab1Val.toUpperCase()+"----"+tab2Val.toUpperCase());

        var changes =RowExists(table2,tab1Val);

        if(!changes[0])
        {
        table1.rows[i].style.backgroundColor = "red";
        instHasChange = true;
        }
}
 function RowExists(table,columnValue)
{
 var hasColumnOrChange = new Array(2);
 hasColumnOrChange[0] = false;
  for(var i=1; i < table.rows.length; i++)
 {

 if(table.rows[i].cells[0].innerHTML == columnValue) /*** why these two does not match**/
 {
   hasColumnOrChange[0] = true;
  }
 return hasColumnOrChange;
}
}

Please suggest what wrong here. (table.rows[i].cells[0].innerHTML == columnValue) never returns true even if all values same.


回答1:


Try and use Jquery's method .text

Depending on the browser(Firefox and Chrome's) innerHTML does not work

JQuery takes care of that issue for you.




回答2:


most browsers have bugs with innerHTML and it is not a recommended property to use. different browsers will do different things, usually messing with whitespace, adding/removing quotes, and/or changing the order of attributes.

long story short, never rely on innerHTML.

In it's place, I would recommend using some of the DOM traversal functions, such as .firstChild and .nodeValue. Notice that these are sensitive of white space, and will have to be tweaked if you have anything else in your TD than just text.

http://jsfiddle.net/tdN5L/

if (table.rows[i].cells[0].firstChild.nodeValue === columnValue)

Another option, as pointed out by Micah's solution, is using a library such as jQuery, which will let you ignore most of these browser issues and DOM manipulation pain. I would not recommend bringing in the overhead of jQuery just for this issue, though.

related:

Firefox innerHTML Bug?

innerHTML bug IE8

innerHTML removes attribute quotes in Internet Explorer



来源:https://stackoverflow.com/questions/11584542/why-innerhtml-does-not-return-true-when-compared-with-same-string-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!