To change the text color of a paragraph using jQuery, we simply can use the css() method to change the styles of an element.
$("#p1").css("color", "green");
Let’s say we have the following HTML:
<div id="div">
<p id="p1">We will change the color of this text.</p>
</div>
If we want to change the color of the paragraph to green, we will use the jQuery css() method in the following JavaScript code.
$("#p1").css("color", "green");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#p1").css("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 background color to green.
$("#p1").css("color", "#00FF00");
Using jQuery to Change the Color of Text with a Click
To change the color of text using jQuery, we can combine the css() method 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.
<div>
<p id="p1">This is some text</p>
<p id="p2">This is some text</p>
<div id="click-me">Change text color</div>
</div>
We can utilize both the jQuery click() and css() methods to change the color of the first line of text.
Here is the JavaScript code:
$("#click-me").click(function(){
$("#p1").css("color", "green");
});
The final code and output for this example of how to change the text color using jQuery is below:
Code Output:
This is some text
This is some text
Full Code:
<div>
<p id="p1">This is some text</p>
<p id="p2">This is some text</p>
<div id="click-me">Change text color</div>
</div>
<script>
$("#click-me").click(function(){
$("#p1").css("color", "green");
});
</script>
Hopefully this article has been useful for you to understand how to use jQuery to change the color of some text.
Leave a Reply