0

I have looked around and I haven't really been able to find anything that solves my problem. There is a post using buttons but I can't seem to modify it for my needs.

I am trying to use only one event listener for multiple selects. I'd like to return the id of the select, and the value selected but as far as I can figure I either need to use document.getElementById("ID").addEventListener('change',func(),true) for each id or document.getElementsByTagName('select').addEventListener('change', func(), true) and I get an error that says:

selection.addEventListener is not a function. (In 'selection.addEventListener('change', func(), true)', 'selection.addEventListener' is undefined)

I was hoping someone could take a moment and show me where I am going wrong or if I need to use a different method to accomplish my task.

thanks for the help

demuro1
  • 289
  • 1
  • 4
  • 15

1 Answers1

0

The method getElementsByTagName returns HTMLCollection of elements, and not a DOM Element, so you can't use addEventListener on that.

What you can do is go over all the elements in the HTMLCollection and add the event you want to them:

let selectElements = document.getElementsByTagName('select');
Array.prototype.forEach.call(selectElements, function(el) {
    eladdEventListener('change', func(), true)
})
Dekel
  • 60,707
  • 10
  • 101
  • 129