Combining multiple elements with .addEventListener

Hi campers!

I haven’t been here for a while, so first of all I hope you are doing well.

My question is, how can I add multiple elements to my .addEventListener?

I have tried with forEach and an array. Here is my code.

document.querySelector('.openbtn').addEventListener('click', () => { 
    document.getElementById('sideBar').style.display = 'block';
    document.getElementById('openbtn').style.display = 'none';
})

[document.querySelector('.sideBar'), document.querySelector('.sections'), document.querySelector('.footer')].forEach(item => {
    item.addEventListener('click', function () {
            document.getElementById('sideBar').style.display = 'none';
        })
  })

And in case you need, codepen is here.

Thank you in advance.

  1. sideBar is an id not a class document.querySelector('#sideBar')

  2. You also misspelled class="feeter"

Edit: I just noticed that the code chokes on the first code block if you do not end it with a semicolon ;

document.querySelector('.openbtn').addEventListener('click', () => {
  document.getElementById('sideBar').style.display = 'block';
  document.getElementById('openbtn').style.display = 'none';
});
1 Like