0
I want only a button to change its innerText at a particular time, instead it changes the two at the same time
3 Antworten
+ 1
I'mabiodun,
Your original post snippet maps the buttons' "click" event to `change()` function by using "onclick" attribute.
That means `change()` will be called when any of the buttons were clicked, and we just need to refer to the one button that was clicked by using event.target
If you have many buttons then it's better to use `addEventListener()` in a loop to attach an event handler for each button rather than writing "onclick='change()'" for each <button> element, which obviously be a tiresome work.
https://code.sololearn.com/WHiDQKOncKsZ/?ref=app
+ 1
Ipang what if the button is more than two, I just made this up as example. I can do it without iteration but I want to know how to do it using iteration
0
You don't need a for...loop to change one button only, this is all you need ...
const change = function()
{
const btn = event.target;
if ( btn.innerText == "ON" )
{
btn.innerText = "OFF";
}
else
{
btn.innerText = "ON";
}
}