Home > Mobile >  Click in JS loop undefined
Click in JS loop undefined

Time:09-28

I have an interation loop on which I need to click on every element:

var spans = document.getElementsByClassName('span')
for (var i = 0; i < spans.length; i  = 1) {
    i.click(function() {
      console.log("Clicked")
    });
}

I get i.click is not a function error. ¿What am I missing?

Thanks!

CodePudding user response:

i is the index, not the element. This is how you would fix your code:

var spans = document.getElementsByClassName('span')
for (var i = 0; i < spans.length; i  = 1) {
  spans[i].click(function() {
    console.log("Clicked")
  });
}

But 'click' also doesn't take a callback. This is how your code should look like in 2022:

const spans = document.getElementsByClassName('span')
for (const span of spans) {
  span.click();
  console.log("Clicked")
}
  • Related