skrttt44
skrttt44

Reputation: 39

How to change button color onclick using javascript only?

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.

Upvotes: 3

Views: 37574

Answers (4)

Ashar Siddiqui
Ashar Siddiqui

Reputation: 91

Using jquery, try this. if your button id is say id= clickme

$("clickme").on('çlick', function(){

    $(this).css('background-color', 'grey'); .......

Upvotes: 0

Ele
Ele

Reputation: 33736

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>

Upvotes: 6

jasinth premkumar
jasinth premkumar

Reputation: 1413

The className property sets or returns the class name of an element (the value of an element's class attribute).

function submitButtonStyle() { 
document.getElementsByClassName("stylebutton")[0].style.backgroundColor = "red"; }
<button onclick="submitButtonStyle()" type="submit" class="stylebutton"> 
Submit </button>
JS:

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Source

Upvotes: 0

Maya
Maya

Reputation: 1547

document.getElementsByClassName returns an array of objects, since many tags may have the same class. If you know that only one object has a given class, use

document.getElementsByClassName("stylebutton")[0].style.backgroundColor = "red";

Upvotes: 2

Related Questions