JavaScript Code


How to change text color of paragraph using JavaScript?


Tutorials using JS

Change text color of Paragraph using JavaScript

In this tutorial, you shall learn how to set/change text color of a paragraph element using JavaScript.

Solution

To set or change the text color of a paragraph element using JavaScript, we can use Element.style.color property. Get the paragraph element and set its style.color property with the required color value.

paragraphElement.style.color = 'blue';

Program

When user clicks on the Click me button, we get the paragraph with the id message and set its text color using style.color property.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<p id="message">This is a paragraph. Welcome to JavaScript tutorials.</p>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
	//get the paragraph element by id
	const myPara = document.getElementById("message");
	//set the text color of the paragraph
	myPara.style.color = 'blue';
});
</script>

</body>
</html>


Copyright @2022