I have 3 buttons having class name "btn"; How can select all button by using addEventListener and forEach? I don't select one by one HTML codes:
<div class="display">
<input type="number" class="text">
</div>
<div class="buttons">
<input type="button" value="1" class="btn">
<input type="button" value="2" class="btn">
<input type="button" value="3" class="btn">
</div>
JS code:
const display = document.querySelector(".text"),
btn = document.querySelectorAll(".btn");
btn.addEventListener("click", buttons);
function buttons() {
display.value = btn.value;
};
You can use for...of
for this like:
const btns = document.querySelectorAll('.btn');
for (const btn of btns) {
btn.addEventListener('click', function() {
console.log(this.value);
});
}
<input type="button" value="1" class="btn">
<input type="button" value="2" class="btn">
<input type="button" value="3" class="btn">
For using forEach()
, you will have to convert btns
DOM nodes to an array first using Array.from()
like:
const btns = document.querySelectorAll('.btn');
Array.from(btns).forEach(function(btn) {
btn.addEventListener('click', function() {
console.log(this.value);
});
});
<input type="button" value="1" class="btn">
<input type="button" value="2" class="btn">
<input type="button" value="3" class="btn">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With