In the following example, we have three buttons and we want to change their background color when they are clicked. Please have a look over the code example and steps given below.
HTML & CSS
We have 4 elements in the HTML file (1 div and 3 button). The div element is just a wrapper for the rest of the elements.
The 3 button elements have “Primary”, “Danger”, and “Success” as their inner text.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We have selected all 3 button elements using the document.querySelector() method and stored them in btnPrimary, btnDanger, and btnGreen variables.
We have attached a click event listener to all the button elements.
The button element has style property. This property points to an object which contains all style-related properties. The backgroundColor property is one of them. We will use this property to change the color of the button element
Upon click of the primary button, we will change the color of the button to “#337ab7”, which is a light blue color.
Upon click of the danger button, we will change the color of the button to “#c9302c”, which is a maroon color.
Upon click of the success button, we will change the color of the button to “#4cae4c”, which is a green color.
let btnPrimary = document.querySelector('#primary');
let btnDanger = document.querySelector('#danger');
let btnSuccess = document.querySelector('#success');
btnPrimary.addEventListener('click', () => btnPrimary.style.backgroundColor = '#337ab7')
btnDanger.addEventListener('click', () => btnDanger.style.backgroundColor = '#c9302c')
btnSuccess.addEventListener('click', () => btnSuccess.style.backgroundColor = '#4cae4c')