Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Object #<NodeList> has no method 'addEventListener'

I have one button element in a relatively simple HTML file. I'm trying to add an event listener, but I keep getting errors, and I'm not sure why: Uncaught TypeError: Object #<NodeList> has no method 'addEventListener'

I am trying to learn the 'addEventListener' method, but I'm not understanding what's wrong with what I'm doing:

HTML:

<button>guess</button>

JS:

var myButton = document.getElementsByTagName('button');

myButton.addEventListener('click', doSomething, false);

var doSomething = function(e){
    console.log('I was clicked!');

    e.preventDefault();
    return false;
};

Thank you to those who helped.

In conclusion for any other newbies that might be having this problem:

  1. When you use document.getElementsByTagName() or any other method that returns a NodeList, you have to specify which node you want to manipulate.
  2. Make sure you add the event listener after the function has been declared.
like image 692
Lindsay Avatar asked Dec 01 '25 11:12

Lindsay


1 Answers

getElementsByTagName('button') returns a list, not an element. You need to add your EventListener to the first element in that list.

Try:

var myButton = document.getElementsByTagName('button')[0];

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!