Changing the color of a button using javascript

I had a problem with changing the color of a button using a simple function, the color does not change at all.

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script language="JavaScript"> function changeColor(){ document.getElementsByTagName('button').style.backgroundColor="green"; } </script> </head> <body > <form action="/action_page.php" method="get" name="form1"> <input type="text" id="campoDeFlores"> <button type="button" onclick="changeColor()" name="1">1</button> <button type="button" name="2">2</button> <button type="button" name="3">3</button> </form> </body> </html> 

Any idea why it doesn't work?

+5
source share
4 answers

document.getElementsByTagName returns a list of elements, not a single element. You need to convert it to an array using Array.from and then Array.from over the buttons using Array.map

 function changeColor(){ Array.from(document.querySelectorAll('button')).map(function(button) { button.style.backgroundColor="green"; }) } 
+4
source

Try the following:

HTML

 <form action="/action_page.php" method="get" name="form1"> <input type="text" id="campoDeFlores"> <button type="button" onclick="changeColor(this)" name="1">1</button> <button type="button" name="2">2</button> <button type="button" name="3">3</button> </form> 

Js

 function changeColor(btn) { btn.style.backgroundColor = "green"; } 

Check out this script .

Explanation

At first, I thought you were trying to change the color of all buttons because you used getElementsByTagName , but it looks like you just want to change the color of the button that was pressed. In this case, you do not need to use an array. Just pass in the element that was clicked on the function, and then change the color of the specific button.
+1
source

You are better off using id="myButton" and document.getElementById('myButton') to specifically select a button instead of each button .

+1
source

Make the following changes:

  • allows your changeColor function to accept an HTMLElement as a parameter.
  • Go to the changeColor() button. + Change onclick="changeColor()" in the button element onclick="changeColor(this)"

 function changeColor (htmlEl) { htmlEl.style.backgroundColor="green"; } 
 <form action="/action_page.php" method="get" name="form1"> <input type="text" id="campoDeFlores"> <button type="button" onclick="changeColor(this)" name="1">1</button> <button type="button" name="2">2</button> <button type="button" name="3">3</button> </form> 
0
source

Source: https://habr.com/ru/post/1265881/


All Articles