admin管理员组

文章数量:1245106

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.

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.

Share Improve this question asked Feb 17, 2018 at 19:20 skrttt44skrttt44 391 gold badge1 silver badge4 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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>

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

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

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

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

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

本文标签: How to change button color onclick using javascript onlyStack Overflow