How to change button color onclick using javascript only?

skrttt44 picture skrttt44 · Feb 17, 2018 · Viewed 27.5k times · Source

I was trying to make the color of the buttons change using onclick and getElementsByClassName and came up with something like this:

HTML:

<button onclick="submitButtonStyle()" type="submit" class="stylebutton"> 
Submit </button>

JS:

function submitButtonStyle() { 
document.getElementsByClassName("stylebutton").style.backgroundColor = "red"; }

I would be really grateful if you guys gave me a hint about what is lacking in my code/what I should add etc.

Answer

Ele picture Ele · Feb 17, 2018

getElementsByClassName returns an HTMLCollection so you need to get the elements using an index, in your case index === 0 getElementsByClassName[0].

Actually, you don't need to call the function getElementsByClassName, pass the element as param.

function submitButtonStyle(_this) {
  _this.style.backgroundColor = "red";
}
<button onclick="submitButtonStyle(this)" type="submit" class="stylebutton"> 
Submit </button>

Better approach using Event binding and function querySelectorAll

document.querySelectorAll('.stylebutton').forEach(function(e) {
  e.addEventListener('click', function() {
    this.style.backgroundColor = "red";
  })
});
<button type="submit" class="stylebutton"> Submit </button>