Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  113] [ 7]  / answers: 1 / hits: 35893  / 6 Years ago, sat, february 17, 2018, 12:00:00

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.


More From » onclick

 Answers
44

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>




[#55119] Wednesday, February 14, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaidyn

Total Points: 633
Total Questions: 102
Total Answers: 100

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
;