Home > Blockchain >  why when I click on the event it only works sometimes and not always?
why when I click on the event it only works sometimes and not always?

Time:12-28

let addToCart = document.querySelectorAll('#app')

addToCart.forEach((btn) => {
    btn.addEventListener('click',(e) => { 
    
    if (e.target.classList.contains('add-to-cart')) {
        console.log('click!')
    }
    
    })
})

I am working with dynamic buttons and template literals to make a shopping cart. I fetch to extract the information from mongo DB, but when I click the add request button it only works a few times.

Thanks in advance

CodePudding user response:

You're using querySelectorAll('#app')
The # means you want to get an ID, But querySelectorAll select mutiple Ids and document HTML accept only one id per page use instead querySelector('#app').

let app = document.querySelector('#app')

app.addEventListener('click',(e) => {    
    if (e.target.classList.contains('add-to-cart')) {
        console.log('click!')
    }  
})

// Alernative way using querySelectorAll 
/*
const btns = document.querySelectorAll('.add-to-cart');
[...btns].forEach(btn=>btn.addEventListener('click',()=>console.log('click!')))
*/
<div id="app">
<li>
Item 1
<button > </button>
</li>
<li>
Item 2
<button > </button>
</li>
</div>

  • Related