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?

2
  • getElementsByTagName returns an array which means you have to loop to access each element. Commented Mar 24, 2017 at 17:26
  • See this example: jsfiddle.net/7q1zk42w. Commented Mar 24, 2017 at 17:33

6 Answers 6

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";
    })
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
@NelsonTeixeira I think querySelector is better because the OP might want to change the condition. Isn't forEach just ES6?
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)
oh ok :D Thanks!
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.

Comments

1

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

1 Comment

This is the real solution
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>

Comments

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";
    }
    })
  });


 

Comments

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);}`;

}`*

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.