0

I'm trying to perform a mouseover event on my table rows using Javascript. I understand CSS would better accomplish this task but I would like to learn how to do it in Javascript is well.

Here is my Code:

var tableRows = document.getElementsByTagName('tr');
tableRows.addEventListener("mouseover", rollOver);

function rollOver() {
  alert('you scrolled over a table row');
}
<table>
  <tr>
    <td>
      Cell 1
    </td>
    <td>
      Cell 2
    </td>
  </tr>
  <tr>
    <td>
      Cell 3
    </td>
    <td>
      Cell 4
    </td>
  </tr>
  <tr>
    <td>
      Cell 5
    </td>
    <td>
      Cell 6
    </td>
  </tr>
</table>

Console.log seems to indicate that "addEventListener" is not a function. What am I doing wrong here? Any thoughts?

Thank you!

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Brixsta
  • 605
  • 12
  • 24
  • 2
    The `.getElementsByTagName()` function returns a list of elements. That list object does not have an `.addEventListener()` method. You have to iterate over the list and call that function on the individual DOM elements in the list. The attached duplicate isn't about mouseovers or tr elements, but it is the same problem with trying to apply `.addEventListener()` to a list so the solution is the same as what you need. – nnnnnn Apr 10 '17 at 07:22
  • Just upvoted, because I can hardly figure out why your question had been downvoted. – Brice Coustillas Mar 28 '21 at 14:56

1 Answers1

2

As tableRows will return object .addEventListener will not work with it...so looping them and use will..

var tableRows = document.getElementsByTagName('tr');

for (var i = 0; i < tableRows.length; i += 1) {
  tableRows[i].addEventListener('mouseover', function(e){
  console.log("sdsd");
  }); 
  // or attachEvent, depends on browser
}
<table>
  <tr>
    <td>
      Cell 1
    </td>
    <td>
      Cell 2
    </td>
  </tr>
  <tr>
    <td>
      Cell 3
    </td>
    <td>
      Cell 4
    </td>
  </tr>
  <tr>
    <td>
      Cell 5
    </td>
    <td>
      Cell 6
    </td>
  </tr>
</table>
BEJGAM SHIVA PRASAD
  • 2,181
  • 1
  • 18
  • 27