0

I want only a button to change its innerText at a particular time, instead it changes the two at the same time

https://code.sololearn.com/WhBkhshcktJE/?ref=app

20th Jul 2021, 9:08 AM
Olorunsogo Abiodun Isaac
Olorunsogo Abiodun Isaac - avatar
3 Respuestas
+ 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
20th Jul 2021, 10:26 AM
Ipang
+ 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
20th Jul 2021, 9:56 AM
Olorunsogo Abiodun Isaac
Olorunsogo Abiodun Isaac - avatar
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"; } }
20th Jul 2021, 9:28 AM
Ipang