0

I have a problem with getElementById and getElementsByClassName.

This code works fine

document.getElementById("dropdown-menu1").addEventListener('click', function (event) {
            alert("click outside");
            event.stopPropagation();
        });

But when I try to use it with getElementsByClassName it's stop working.

var menu1 = document.getElementsByClassName("dropdown-menu");
        document.menu1.addEventListener('click', function(event) {
        alert("click outside");
        event.stopPropagation();
 });

I don't know why. I get no error.

Estudio 3551
  • 170
  • 3
  • 14
  • 2
    FYI `menu1` and `document.menu1` have no relation at all. I would also be very surprised if you weren't getting an error like _"Uncaught TypeError: Cannot read property 'addEventListener' of undefined"_ – Phil Aug 22 '21 at 23:55
  • 1
    [*getElementsByClassName*](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) returns a [live *NodeList*](https://developer.mozilla.org/en-US/docs/Web/API/NodeList), whereas [*getElementById*](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) returns a single element (or null). – RobG Aug 23 '21 at 00:21
  • Thanks for your help. Finally I can solved using getElementById. – Estudio 3551 Aug 24 '21 at 04:17

0 Answers0