IE9 Compatibility Mode Error: Unable to get value of the property '0': object is null or undefined

682 views Asked by At

I am trying to get the children of a <tr> element in a table. I need to get each of the individual <td> cells. I cannot use jQuery, only JavaScript for infrastructure reasons. My JavaScript looks like this:

var feeTable = document.getElementById("feeTable");

function gatherRowData() {
  console.log("gathering row data");
  var rows = this.parentNode.children; //This is where it fails.
  var state = rows[0].innerText;
  var county = rows[1].innerText;
  var city = rows[2].innerText;
  console.log("state: " + state);
  document.getElementById("state_code").value = state;
  document.getElementById("county_name").value = county;
  document.getElementById("city_name").value = city;
}

//Loop through Vehicle Fee Changes to find any empty cells in county, city, or start date.
for (var i = 0; row = feeTable.rows[i]; i++) {
  var county = row.cells[1];
  var city = row.cells[2];
  var startDate = row.cells[6];

  if (county.innerText == "") {
    county.style.backgroundColor = "#FF0000";
    showError(invalidCells);
  }
  if (city.innerText == "") {
    city.style.backgroundColor = "#FF0000";
    showError(invalidCells);
  }
  if (startDate.innerText == "") {
    startDate.style.backgroundColor = "#FF0000";
    showError(invalidCells);
  }

  if (document.addEventListener) {
    row.cells[8].addEventListener("click", gatherRowData);
  } else if (document.attachEvent) { //Support for IE
    row.cells[8].attachEvent("onclick", gatherRowData);
  }
}

The onClick listeners work just fine, but when I try to get the children of the table row, it gives me the error: Error message: Unable to get value of the property '0': object is null or undefined It works fine in all other browsers, and IE9 without compatibility mode on (it is required to function with compatibility mode). What am I missing that would allow me to get the children of the tr element?

2

There are 2 answers

0
Travis Baker On BEST ANSWER

I found a solution to my problem. It turns out that when you use attachEvent to attach an event listener, the reference to this in the JavaScript event handler function doesn't actually reference the object that is being clicked on. It represents the Window object as a whole. I had to use a slightly less elegant solution:

row.cells[8].onclick = gatherRowData;

This is the only solution that would work for the versions of IE that don't support addEventListener. Using this solution, the rest of my code worked fine and this referenced the <td> element as it was supposed to.

0
Pandiyan Cool On

This error may occur when the feeTable has null value

var feeTable = document.getElementById("feeTable");

Try writing values of feeTable in console, and check it has proper value other than null.