-1

I'm learning about the addEventListener on JavaScript, and when I enter this code:

test();
function test(){
    var td = document.getElementsByTagName("td");
    td.addEventListener('mouseenter', function(){
        td.style.background = "green";
    });
}

it didn't work. Can anyone explain why?

NewbieCoder
  • 23
  • 1
  • 5
  • `.getElementsByTagName()` returns a list. That list does not have an `.addEventListener()` method. The individual elements in the list have an `.addEventListener()` method, so you need to iterate over the list (as in the linked duplicate). – nnnnnn Aug 16 '17 at 03:03
  • Document.getElementsByTagName return a node list, if u want to apply addEventListener you need to use Array.prototype.slice.apply to documet.getElementsByTagName, and after use a for or forEach function to apply the addEventListener to every td element in array – Risa__B Aug 16 '17 at 03:06

1 Answers1

0

getElementsByTagName return a HTMLcollection, So you need to pass the index of the element on which you want to add the event, or loop over the collection to add the event to each of the element

function test(){
    // selecting only first element from the collection
    var td = document.getElementsByTagName("td")[0];
    td.addEventListener('mouseenter', function(){
        td.style.background = "green";
    });
}

test();

Adding addListener to all elements in the collection

function test(){
var cells = table.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
cells[i].addEventListener('mouseenter', function(){
            this.style.background = "green";
        });

}};
test()
brk
  • 48,835
  • 10
  • 56
  • 78