Click here to Skip to main content
15,887,683 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:

HTML
<pre><!DOCTYPE html>
<html>
<head>
    <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>
</head>
<body>
    <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>

    <script>
        const gombok=document.getElementsByTagName('button')

        for(i=0;i<gombok.length;i++){
            x=gombok[i]
            x.onclick=function(){
                myFunction(x)
            }
        }
        function myFunction(btn){
            btn.textContent='Button Clicked!'
        }
    </script>
</body>
</html>
Posted
Updated 21-Jul-22 1:58am

1 solution

check out the addEventListener[^]
 
Share this answer
 
v2
Comments
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 () {
this.textContent='Clicked';
});
}
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