I need to listen for clicks on <input/>
elements.
This is my code
<script>
document.getElementsByClassName("form-control").addEventListener("click", function(e){
alert("Listener added");
});
</script>
But I'm getting this error:
Uncaught TypeError: document.getElementsByClassName(...).addEventListener is not a function
Any ideas?
CodePudding user response:
Instead of returning single element getElementsByClassName()
returns collection of elements.That's why we have to loop that collection of elements or simply you can overcome this problem by adding document.getElementsByClassName('form-control')[0]
Here,I rewrite the code:
`
document.getElementsByClassName("form-control")[0].addEventListener("click", function(e){
alert("Listener added");
});
`
Hope I was able to answer your question. Here is a tutorial to reinforce your learning.
CodePudding user response:
The reason why you are getting this error is because getElementsByClassName returns an array of elements but you need to have a single element in order to add an event listener. If you want to add event listener to all elements, you can simply loop through the array as shown below.
document.getElementsByClassName("form-control").forEach(element => {
element.onclick = event => {
alert("Listener added");
}
});
If you want to add event listener to a specific element, you can simply access it by indexing the array.
document.getElementsByClassName("form-control")[0].addEventListener("click", function(e){
alert("Listener added");
});
You can also use ids for specific elements in order to access them more easily.