In the following example, we have some random text content. We also have three buttons red, blue, and green. We want to change the color of text content depending upon which button is clicked. Please have a look over the code example and steps given below.
HTML & CSS
We have 6 elements in the HTML file (2 div, 3 button, and 1 p). The div element with a class of container is just a wrapper for the rest of the elements.
The 3 button elements have “Red”, “Blue”, and “Green” as their inner text.
The paragraph element contains some random text content. We will change its color on the button click.
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 and the paragraph element using the document.querySelector() method and stored them in btnRed, btnBlue, btnGreen, and content variables respectively.
We have attached a click event listener to all the button elements.
The paragraph element has style property. This property points to an object which contains all style-related properties. The color property is one of them. We will use this property to change the color of the text inside the paragraph element.
Upon click of the red button, we will change the text color to red.
Upon click of the blue button, we will change the text color to blue.
Upon click of the green button, we will change the text color to green.
let btnRed = document.querySelector('#btnRed');
let btnBlue = document.querySelector('#btnBlue');
let btnGreen = document.querySelector('#btnGreen');
let content = document.querySelector('p');
btnRed.addEventListener('click',() => content.style.color = 'red');
btnBlue.addEventListener('click',() => content.style.color = 'blue');
btnGreen.addEventListener('click',() => content.style.color = 'green');