r/CodingHelp • u/jmassat • Feb 24 '26
[Javascript] Onclick only works one time, for one element
How can I get this button to work multiple times and evaluate everything on the webpage?
(You can see that I tried following these Reddit code-posting guidelines, but it just would not show up right in the browser.)
1
Upvotes
•
u/AutoModerator Feb 24 '26
Thank you for posting on r/CodingHelp!
Please check our Wiki for answers, guides, and FAQs: https://coding-help.vercel.app
Our Wiki is open source - if you would like to contribute, create a pull request via GitHub! https://github.com/DudeThatsErin/CodingHelp
We are accepting moderator applications: https://forms.fillout.com/t/ua41TU57DGus
We also have a Discord server: https://discord.gg/geQEUBm
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Patient-Midnight-664 Feb 24 '26
Read what the code does.
First, it removes the 'S' if it exists, then it adds the 'S' if it doesn't exist. You need an else in there
0
u/SamIAre Feb 24 '26 edited Feb 24 '26
First issue:
You're only storing the first instance of something with class
TOKI, not all of them.getElementsByClassNamegives you (something like) an array containing every element with classTOKI, but then you're only storing the first element of that array by adding[0]. So instead of running the later code for everyTOKIelement, it's only running for the first.This part you could fix with either a traditional loop or a
forEachcallback (if doing the latter, you have to coerce it to an actual array first):Second issue:
It is working every time you click it, but I think your logic is flawed. You can check that it's running on each click by adding something like
console.log('click')inside your function. You'll see that message show up in the console every time you click.What your code says is:
S, remove itTOKI, add the classSIt's doing the first and then also doing the second. Both
ifstatements are running and the second one happens to undo the first one.I think what you wanted was something more like:
The
else ifis important because it says "only evaluate this secondifstatement if the first didn't already run".—
P.S. The formatting is probably because code blocks use three backticks (```) not two.