Search code examples
javascriptonmouseover

What is difference between these two statements?


     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'; 
          }            
        }

Solution

  • 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