'Chrome extension: Click Event Listener won't initiate
I'm working on a Chrome extension and I have an error that gets returned whenever I try to add a "click" event to a class.
Error in event handler for 'undefined': Object #<NodeList> has no method 'addEventListener' TypeError: Object #<NodeList> has no method 'addEventListener'
Here's my code for the function (popup.js):
listElements: function(elements) {
iHTML = '';
for (var i = 0; i < elements.length; i++) {
...
...
iHTML += '<div class="theBtn">btn</div>';
...
...
}
$('popup_content').innerHTML = iHTML;
var btnElements = document.getElementsByClassName('theBtn');
if (btnElements.length > 0) {
btnElements.addEventListener("click", clicked);
}
}
I also tried each() and that didn't work either. Same error message. It logs btnElements perfectly fine too. Any ideas?
Solution 1:[1]
Since you are using jQuery instead of
var btnElements = document.getElementsByClassName('theBtn');
if (btnElements.length > 0) {
btnElements.addEventListener("click", clicked);
}
subscribe to click event as:
$('.theBtn').click(clicked);
getElementsByClassName returns NodeList, and you can't attach event to it as btnElements.addEventListener. However this should work:
var btnElements = document.getElementsByClassName('theBtn');
for (var i = btnElements.length; i--;) {
btnElements[i].addEventListener("click", clicked);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
