How many times the "HTML Button" has been clicked?
We have several buttons on a HTML page that we want to save the number of click on each button. on the other hand, we are not allowed to access ...
How many times the "HTML Button" has been clicked?
What's the issue?
We have several buttons on a HTML page that we want to save the number of click on each button. On the other hand, we are not allowed to access the DOM (for example: we cann't write number of clicks on the data-click on a DOM), because the access to the DOM is not good for performance and it's very expensive.
HTML BUTTONS:
<button class="btn">0</button>
<button class="btn">0</button>
<button class="btn">0</button>
<button class="btn">0</button>
<button class="btn">0</button>
What's the solution?
First of all, we collect all the buttons in an array:
const btns = [...document.querySelectorAll('btn')];
When you console it (console.log('btns')
) we expect to see the following output:
2- We make an empty array with the number of buttons btns
const btnContainer = new Array(btns.lenght);
3- We add event listener to each button and store their values on btnCountainer.
btns.forEach((btn, i) => {
btnContainer[i] = 0;
btn.addEventListener('click', () => btn.textContent = ++btnContainer[i]);
});
For every issue there is a lot of solution and algorithms, so the solution which I showed, was only one of them. If you have another way, please share it with me .
Thanks for your attention.