To change the text color of a paragraph using JavaScript, we simply use the Style color property.
document.getElementById("div1").style.color = "green";
Let’s say we have the following HTML:
We will change the color of this text.
If we want to change the color of the paragraph to green, we will use the color property in the following JavaScript code.
document.getElementById("p1").style.color = "green";
The second argument can be any valid CSS color. So for example, we could use the hexadecimal value for green to change the color to green.
document.getElementById("p1").style.color = "#00FF00";
Using JavaScript to Change the Color of Text with a Click
To change the color of text using JavaScript, we can target the style color property with a click event.
Let’s say we have the following HTML and we want to change the color of the first paragraph to green.
This is some text
This is some text
We can utilize both the style color property of #p1 along with an onclick event to change the color of the first line of text.
Here is the JavaScript code:
function clickFunction() {
document.getElementById("p1").style.color = "green";
}
The final code and output for this example of how to change the text color using JavaScript is below:
Code Output:
This is some text
This is some text
Full Code:
This is some text
This is some text
<script>
function clickFunction() {
document.getElementById("p1").style.color = "green";
}
</script>
Hopefully this article has been useful for you to understand how to use JavaScript to change the color of some text.