bikashroy
bikashroy

Reputation: 7

I am getting some errors in console while using events

I was trying click events while I open my browser console I am getting this error: events.js:2 Uncaught TypeError: button.addEventListener is not a function at events.js:2 (anonymous) @ events.js:2

Check my code

Upvotes: 0

Views: 237

Answers (2)

Dan Knights
Dan Knights

Reputation: 8378

document.getElementsByTagName returns an HTML collection. You can either select a specific one using it's index: document.getElementsByTagName('button')[0] or loop through and add an event listener to each one:

for (let i of buttons) {
    i.addEventListener('click', () => {
        console.log('CLICK!!!')
    })
}

Upvotes: 0

habiiev
habiiev

Reputation: 440

Function getElementsByTagName returns an array of all buttons, so if you have only one button you can do document.getElementsByTagName('button')[0].

Upvotes: 2

Related Questions