'Adding the same event listener to multiple elements

I saw similar questions but either they aren't close enough to what I want or are just as unclear as their respective answers -- let's see:

What I have: The following chunk of code:

        addEventListener("load", function() {
            for(var x in document.getElementsByName("rbTipo")) {
                document.getElementsByName("rbTipo")[x].addEventListener("change", function() {
                    if(document.getElementById("rbTipoA").checked) {
                        document.getElementById("painelAluno").style.display = "block";
                        document.getElementById("painelEscola").style.display = "none";
                    }
                    else if(document.getElementById("rbTipoE").checked) {
                        document.getElementById("painelAluno").style.display = "none";
                        document.getElementById("painelEscola").style.display = "block";
                    }
                    else {
                        document.getElementById("painelAluno").style.display = "none";
                        document.getElementById("painelEscola").style.display = "none";
                    }
                });
            }
        });

What it should do:

  • For each DOM element with name="rbTipo", add it the change listener;
  • Change CSS properties of third-party elements on their change.

What it's doing wrong:

Apparently doc[...]byName("rbTipo")[x] is not selecting the elements themselves. Means x is not the current iteration index of the array returned from getElementsByName?

What I tried:

Give each name="rbTipo" element their own listener. Doesn't seem logical since we're talking about doing something for multiple elements. Not a big deal since I have only two but I'll be doing this really really often, and not always with "just two" indexes.



Solution 1:[1]

Find all the elements with name="rbTipo", and loop through them, adding the listener to each:

var rbTipos = document.querySelectorAll('[name="rbTipo"]');
for (var i = 0; i < rbTipos.length; i++) {
  rbTipos[i].addEventListener('change', myEventFunction);
}

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 dirn