Change color of button with javascript
Asked Answered
T

6

7

I'm having trouble changing the color of a button with a simple function, the color doesn't 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>

Why does it not work?

Tildy answered 24/3, 2017 at 17:25 Comment(2)
getElementsByTagName returns an array which means you have to loop to access each element.Pneumectomy
See this example: jsfiddle.net/7q1zk42w.Pneumectomy
Z
6

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

function changeColor(){
    Array.from(document.querySelectorAll('button')).map(function(button) {
               button.style.backgroundColor="green";
    })
}
Zermatt answered 24/3, 2017 at 17:31 Comment(4)
Just to complement: you can also do this changing document.querySelectorAll('button') to document.getElementsByTagName('button'). Also you could use .forEach instead of .map as you don't need to return a result.Kore
@NelsonTeixeira I think querySelector is better because the OP might want to change the condition. Isn't forEach just ES6?Zermatt
OK. Just telling the OP that option. About forEach being ES6 only, no it isn't: developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/… (see Specifications section)Kore
oh ok :D Thanks!Zermatt
P
1

Try this:

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 this Fiddle.

Explanation

At first I thought you were trying to change the color of all the buttons because you were using getElementsByTagName but it looks like you just want to change the color of the button that was pressed. In that case you don't need to use an array. Just pass the element that was clicked to the function and then change that specific button's color.

Pneumectomy answered 24/3, 2017 at 17:34 Comment(0)
K
1

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

Kierakieran answered 24/3, 2017 at 17:35 Comment(1)
This is the real solutionEasterling
B
0

Make following changes:

  • allow your changeColor function to accept a HTMLElement as parameter.
  • Pass reference to button to changeColor(). Change onclick="changeColor()" in button element to 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>
Berry answered 24/3, 2017 at 17:36 Comment(0)
L
0

If you have a lot of button and you want to color and uncolor it by clicking it.you can use if statement inside event listener.This feature is used specific in booking something.

HTML

<button class="btnco">1</button>
<button class="btnco">2</button>

CSS

.btnco{

     background-color: green;
    }

JS

document.querySelectorAll('.btnco').forEach(function(e) {
    e.addEventListener('click', function() {
        if (this.style.backgroundColor=="red"){
            this.style.backgroundColor="green"
        }else{
      this.style.backgroundColor = "red";
    }
    })
  });


 
Lyricism answered 6/5, 2022 at 3:48 Comment(0)
A
0

im testing *thisfunction randomcolour(){ document.getElementsByTagName('button').style.backgroundColor=${ var num = Math.floor(Math.random() * Math.pow(2, 24)); return '#' + ('00000' + num.toString(16)).substr(-6);}`;

}`*

Adaptive answered 30/6, 2023 at 20:40 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Kipton

© 2022 - 2024 — McMap. All rights reserved.