views:

410

answers:

1

I have a pane with a set of javascript-generated tables, each with a unique ID and 4 cells, and I use the following Javascript code to set the background color for one of these tables. It works fine in Firefox, but it crashes Safari the first time it tries to set the background color (in the if statement). Any ideas why?

<script language='Javascript'>
  function colortree(source) {
    var el=parent.frames['tree-pane'].document.getElementsByTagName('table');
    for (var i=0;i<el.length;i++) {
        var id = el[i].id;
        if (id) {
           var cell = el[i].getElementsByTagName('td')[3];
           if (id == source) { cell.style.backgroundColor = 'yellow' }
           else { cell.style.backgroundColor = 'white' };
        }
    }
    return false;
  }
</script>
+3  A: 

You should always test the existence of array indices if there's any chance they don't exist

e.g.

<script language='Javascript'>
  function colortree(source) {
    var cells, cell, id;
    var el=parent.frames['tree-pane'].document.getElementsByTagName('table');
    for (var i=0;i<el.length;i++) {
        id = el[i].id;
        if (id) {
           cells = el[i].getElementsByTagName('td');
           if (cells[3]) {
               cell = cells[3];
               if (id == source) { cell.style.backgroundColor = 'yellow' }
               else { cell.style.backgroundColor = 'white' };
           }
        }
    }
    return false;
  }
</script>
Jonathan Fingland