简体   繁体   中英

Event listener doesnt work on some HTML elements

I have 2 groups of HTML buttons, all with the class btn .

 const btn = document.querySelectorAll('.btn'); const btnArray = Array.from(btn); btnArray.forEach((item) => { item.addEventListener('click', () => { console.log('clicked'); console.log(item.value) }); });
 <div class="calculator"> <div class="display"> <p class="output">YES</p> </div> <div class="operations"> <input type="submit" class="btn add" value='+'> <input type="submit" class="btn subtract" value='-'> <input type="submit" class="btn multiply" value='x'> <input type="submit" class="btn divide" value=&divide;> <input type="submit" class="btn clear" value='CLEAR'> </div> <div class="calcBody"> <input type="submit" class="btn seven" value='7'> <input type="submit" class="btn eight" value='8'> <input type="submit" class="btn nine" value='9'> <input type="submit" class="btn four" value='4'> <input type="submit" class="btn five" value='5'> <input type="submit" class="btn six" value='6'> <input type="submit" class="btn one" value='1'> <input type="submit" class="btn two" value='2'> <input type="submit" class="btn three" value='3'> <input type="submit" class="btn zero" value='0'> <input type="submit" class="btn period" value='.'> <input type="submit" class="btn off" value='ON/OFF'> </div> </div>

This works only on the buttons in the calcBody div and not the ones in the operations div. Yet, when I console.log(btnArray) it shows all of the buttons (which is weird).

Can someone tell me why? Thanks.

works perfectly. I checked it on Google Chrome.

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