javascriptinternet-explorerie-compatibility-mode

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


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?


Solution

  • 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.