Click here to Skip to main content
15,844,673 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 10 buttons. I want refer to it by TagName.
With getelementsByTagName, I have got a button collection. I go through with for loop and want that when I click on a button change the textContent to Button Clicked!

But the code changed only the last element to Button Clicked!

What I have tried:

<pre><!DOCTYPE html>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
    <script src='main.js'></script>
    <button class="gomb">1</button>
    <button class="gomb">2</button>
    <button class="gomb">3</button>
    <button class="gomb">4</button>
    <button class="gomb">5</button>
    <button class="gomb">6</button>
    <button class="gomb">7</button>
    <button class="gomb">8</button>
    <button class="gomb">9</button>
    <button class="gomb">10</button>

        const gombok=document.getElementsByTagName('button')

        function myFunction(btn){
            btn.textContent='Button Clicked!'
Updated 21-Jul-22 2:58am

1 solution

check out the addEventListener[^]
Share this answer
folza 21-Jul-22 8:10am    
Does not work Mike. How to modify the code to change the content of the clicked button?
Mike Hankey 21-Jul-22 8:22am    
This worked for me just fine.

var btns = document.getElementsByTagName('button');
for (i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function () {
folza 21-Jul-22 8:37am    
the solution is to declare x with const or let in the for loop

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900