-1

I have established my buttons:

    <div class="calculator">

    <div class="display">
        <p class="numberContent"></p>
    </div>


<div class="operations">
    <button class= 'btn add'>+</button>
    <button class= 'btn subtract'>-</button>
    <button class= 'btn multiply'>x</button>
    <button class= 'btn divide'>&divide</button>
    <button class= 'btn clear'>CLEAR</button>
</div>
and onwards...

In Javascript I would like to be able to add event listeners to all the buttons so I can write the code for the functionality.

I attempted this test but it throws an error: Uncaught TypeError: btn.addEventListener is not a function

let btn= document.querySelectorAll('.btn')
btn.addEventListener('click',()=>{
    alert('clicked')
})

Can someone tell me why I cant add an event listener to all of the members of the class selector. Thanks

nesorethan
  • 95
  • 1
  • 6
  • `.querySelectorAll()` returns a NodeList of all matches, not a single element. To return a single element use `.querySelector()` which will return the first matched element. – pilchard Jan 15 '21 at 22:51
  • I want to select all elements with a class of btn, not just a single element. When I use .querySelector() it just throws: Uncaught TypeError: Cannot read property 'addEventListener' of null – nesorethan Jan 15 '21 at 22:53
  • Then you need to loop through the returned list, or attach the listener to the parent and use `event.target` to access specific buttons. – pilchard Jan 15 '21 at 22:54
  • 1
    There is no element with the class `btn` in your HTML. – blex Jan 15 '21 at 22:56
  • And there's that... – pilchard Jan 15 '21 at 23:00
  • ```class= 'btn.add'>``` is not a applied the btn class its include the word , will be like ```class= 'btn btn.add'>``` – MUHAMMAD ILYAS Jan 15 '21 at 23:01
  • 1
    Trying to put periods in a class name is just asking for selector issues. – Taplar Jan 15 '21 at 23:03
  • I agree with pointing it out, but seems it may be inadvertent and OP meant `class='btn add'` – pilchard Jan 15 '21 at 23:05

1 Answers1

1

As it was already mentioned by others, querySelectorAll() gives you a NodeList. You could create an array from this NodeList and then iterate over it.

const btn = document.querySelectorAll('.btn');
const btnArray = Array.from(btn);
btnArray.forEach((item) => {
  item.addEventListener('click', () => {
    alert('clicked');
  });
});

To make it work, please make sure that your HTML elements have the classes assigned correctly.

<div class="operations">
    <button class= 'btn add'>+</button>
    <button class= 'btn subtract'>-</button>
    <button class= 'btn multiply'>x</button>
    <button class= 'btn divide'>&divide</button>
    <button class= 'btn clear'>CLEAR</button>
</div>
Dharman
  • 30,962
  • 25
  • 85
  • 135
alex-schuster
  • 102
  • 1
  • 7