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:
document.getElementsByTagName() or any other method that returns a NodeList, you have to specify which node you want to manipulate.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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With