I am developing a calculator as a part of the frontEndMasters course but I cannot get the numbers to work, number seven only works. I would like to know if there is any workaround for this since I thought that I could also write an eventlistener for every button but that would violate DRY.
const screens = document.querySelector(".screen");
const clearing = document.querySelector(".calc-buttonBigC");
const buttons = document.querySelector(".calc-button");
console.log(screens.textContent);
clearing.addEventListener('click', () =>{
screens.textContent = "";
});
buttons.addEventListener('click', () =>{
screens.textContent += buttons.textContent;
});
<div class='calc'>
<section class='screen'>
</section>
<section class='calc-buttons'>
<div class='row'>
<button class='calc-buttonBigC'>C</button>
<button class='calc-button-spec'>◄</button>
<button class='calc-button-spec'>/</button>
</div>
<div class='row'>
<button class='calc-button'>7</button>
<button class='calc-button'>8</butbutton>
<button class='calc-button'>9</button>
<button class='calc-button-spec'>x</button>
</div>
<div class='row'>
<button class='calc-button'>4</button>
<button class='calc-button'>5</button>
<button class='calc-button'>6</button>
<button class='calc-button-spec'>-</button>
</div>
<div class='row'>
<button class='calc-button'>1</button>
<button class='calc-button'>2</button>
<button class='calc-button'>3</button>
<button class='calc-button-spec'>+</button>
</div>
<div class='row'>
<button class='calc-buttonBig'>0</button>
<button class='calc-button-spec'>=</button>
</div>
</section>
</div>
I have used querySelector and querySelectorAll with the numbers but I only get the number seven to work.
As far as I understand I have to use a for each loop to get all the numbers to work.
Any suggestions ?
Thank you.
You are using
querySelector(".calc-button"), which looks for the first element that matches the supplied selector and that element is the 7 button in your case. If you want to handle all the buttons, you have to set up an event handler for each, usequerySelectorAll()and then loop over each reference in handler, or (preferably) use "event delegation" to set up one handler for all the buttons and then reference the specific element that triggered the event using the .target property of theevent.Here's an example to get you back on track: