1
     var tr = document.getElementsByTagName('tr');
        tr[0].onmouseover = function(){
          tr[0].style.backgroundColor = '#ccc'; 
        }
        tr[1].onmouseover = function(){
          tr[1].style.backgroundColor = '#ccc'; 
        }
        tr[2].onmouseover = function(){
          tr[2].style.backgroundColor = '#ccc'; 
        }

The first is right, but when I use a for loop as in the following code snippet, I get "Uncaught TypeError: Cannot read property 'style' of undefined".

     var tr = document.getElementsByTagName('tr');
        for(var i=0;i<tr.length;i++){
          tr[i].onmouseover = function(){
            tr[i].style.backgroundColor = '#ccc'; 
          }            
        }
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • This would be easy enough to debug. Place a breakpoint in your debugger on the line where you are setting the background color. Press on the first `tr`. Then examine the value of `i`. That should provide with an idea of what the problem is. –  Jan 16 '16 at 07:30
  • To sum up, you cannot use `i` after the loop has completed (such as inside of a callback). Best to have a `this` or `event` in the handler so that it can look up its DOM element by itself. – Thilo Jan 16 '16 at 07:31

1 Answers1

1

You need to update from

 tr[i].onmouseover = function(){
    tr[i].style.backgroundColor = '#ccc'; 
 }   

to

 tr[i].onmouseover = function(event){
    event.currentTarget.style.backgroundColor = '#ccc'; 
 }   

Problem - By the time you were trying to access tr[i] in the event handler value of i was updated to 3 and hence the error occured

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59