How to change button color onclick using javascript only?

青春壹個敷衍的年華 提交于 2020-03-20 06:15:55

问题


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.


回答1:


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>



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/48845033/how-to-change-button-color-onclick-using-javascript-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!