简体   繁体   中英

JavaScript For Loop not returning anything (not running)?

Ok so, I've got this for loop in a script tag on my EJS page. The current code looks like this:

<script async>
    var removeCartItemButtons = document.getElementsByClassName('btn-danger')
    console.log(removeCartItemButtons)
    var i;
    for (i = 0; i < removeCartItemButtons.length; i++){
        console.log('elem')
        var button = removeCartItemButtons[i]
        button.addEventListener('click', function() {
            console.log('clicked')
        })
    }
</script>

The console.log for the removeCartItemButtons works but the console.log('elem') doesn't run. There are no errors in my cmd nor on the developer tools. I've looked online at different forums to find people doing similar things to me and their's work fine.

I've tried multiple things, and an extra notice is that this is inside the html file and not external.

The end goal of this for loop is to loop through every element with class 'btn-danger' and log when they are clicked. Any help would be amazing!

try running document.getElementsByClassName('btn-danger') in the console.

Additional tip: there is a for of loop in js

check this: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for...of basically:

for(let button of removeCartItemButtons) {
     button.addListener
}

I tried this code in Codepen and it worked. I rewrite your code but technically, just used a different syntax. "async" in your script tag can cause the problem, I can't be sure.

var buttons = document.querySelectorAll('.btn-danger');
[...buttons].forEach(button => {
  console.log('elem')
  button.addEventListener('click', function() {
    console.log('clicked')
  })
})

There must be an issue with your HTML code. Run the snippet below, it's working fine

 var removeCartItemButtons = document.getElementsByClassName('btn-danger') console.log(removeCartItemButtons) var i; for (i = 0; i < removeCartItemButtons.length; i++) { console.log('elem') var button = removeCartItemButtons[i] button.addEventListener('click', function() { console.log('clicked'); alert('clicked'); }) }
 <button class='btn-danger'>Button</button> <br/> <button class='btn-danger'>Button</button> <br/> <button class='btn-danger'>Button</button> <br/> <button class='btn-danger'>Button</button>

removeCartItemButtons.length is 0 because when the snippet ran the DOM was not fully loaded.

Remove async and put your script at the end of your html.

Another option is to use an EventListener like onload to make sure your buttons exist before changing them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM