0

I'm trying to create an event listener on clicking a checkbox (variable is 'box').

Why does box.addEventListener give an error saying 'not a function', whereas it works when I call a function that takes 'box' as a parameter?

  <div class="inbox">
    <div class="item">
      <input type="checkbox">
      <p>Item one</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Item two</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Item three</p>
    </div>

<script>

The code that does work:

    const box = document.querySelectorAll('input');

    function clickMe(param) {
        this.addEventListener('click', function () {
            return console.log('hi');
        });
    };

    clickMe(box);

The code that doesn't work:

const box = document.querySelectorAll('input');

    box.addEventListener('click', function(){
        return console.log('hi');
    })

</script>
Lauren
  • 109
  • 2
  • 11

3 Answers3

1

querySelectorAll() returns a list of matched elements. you'll need to iterate over them and attach a listener to each one

0

If you want to add an Event Listener to all inputs using document.querySelectorAll, you will need to loop through all of the elements with forEach as it returns a list of all the matched elements. You can also use a for loop or Array.prototype.forEach.call as forEach is not as widely supported.

//for each
document.querySelectorAll('input').forEach(i=>{
 i.addEventListener("click", e=>{
  return console.log("hi");
 });
});
//for loop
var inputs = document.querySelectorAll('input');
for(let i = 0; i < inputs.length; i++){
 i.addEventListener("click", e=>{
  return console.log("hi");
 });
}
//Array.prototype.forEach.call
Array.prototype.forEach.call(document.querySelectorAll('input'), function(i){
  i.addEventListener("click", e=>{
  return console.log("hi");
});
});

<div class="inbox">
    <div class="item">
      <input type="checkbox">
      <p>Item one</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Item two</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Item three</p>
    </div>
    <script>
    document.querySelectorAll('input').forEach(i=>{
     i.addEventListener("click", e=>{
      return console.log("hi");
     });
    });
    </script>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

querySelectorAll lists all the elements mentioned. In this case you mentioned 'input' inside querySelectorAll(input).

so do console.log(document.querySelectorAll('input')). so you have do like this.

const box = document.querySelectorAll('input');
console.log(box);
// 'index' value based on which element you need to add event listener. you have three input fields so index will be 0, 1, 2
box[index].addEventListener('click', function () {
            return console.log('hi');
        });
htoniv
  • 1,658
  • 21
  • 40