0

How to use "addEventListener" with "document.getElementsByTagName" to add an event listener to all instances of a specific tag?

Say you have multiple button tags (or any other tag) like so HTML Code <button>Click Here1</button> <button>Click Here2</button> <button>Click Here3</button> JS Code function outPut(){ console.log("Hello") } document.getElementsByTagName("button").addEventListener("click",outPut) Why doesn't the last line in the JS code work? And are there any other ways to implement a thing?

26th Dec 2024, 3:08 PM
Coding Guy
Coding Guy - avatar
2 Answers
+ 2
getElementsByTagName returns an object that contains all the references to the HTML elements. In this example, I used a for...of loop to iterate: https://sololearn.com/compiler-playground/Wiuf2ppwgUz4/?ref=app You can add each eventListener in the loop
26th Dec 2024, 3:13 PM
Lisa
Lisa - avatar
0
Lisa Thank you.
26th Dec 2024, 7:06 PM
Coding Guy
Coding Guy - avatar