Change Text Color Using JavaScript with Example

In this post, we will see how to change text color in HTML using JavaScript with examples.

With JavaScript, we can do DOM manipulation of HTML elements which helps us to change CSS properties of elements like color and font size, etc.

Here is a simple HTML markup with a paragraph.

<body>
  <div>
    <p id="text">Changing color of the text in this paragraph to green.<p>
  <div>
    <script src="script.js"></script>
</body>

Here, we have a line of text in the <p> element whose color we want to change to green using JavaScript.

Change text color with JavaScript

First, we have to target the <p> element with id=”text” using document.getElementById() or document.querySelector() method. Then we will use the style.color property in JavaScript to change the color of the text as desired.

Since we are going to change the color of the text to green, we code as:

const para = document.getElementById("text");
para.style.color = "green";

The above code will change the color of the text automatically when the page loads. However, if you want to do it manually we can add a button to it.

How to change text color on button click in JavaScript

To change the text color of the paragraph on click of a button we will have to add an event Listener which will listen to a click event on the button.

Lets us see it in action:

 <body>
    <div>
      <p id="text">Changing color of the text in this paragraph to green.<p>
    <div>
      <button id="btn">Change Text Color</button>
      <script src="script.js"></script>
  </body>

Added a button with id=”btn”.

const para = document.getElementById("text");
const btn = document.getElementById("btn");

btn.addEventListener("click", colorChange);

function colorChange() {
  para.style.color = "green";
}

So here, we have targeted the button by its id and added a click event listener to it.

Once the button is clicked, the function colorChange() runs which changes the color of the text.

DEMO

change text color javaScript

Edit n3hsx

Related Topics:

JavaScript- Show and hide div on button click

Copy Text From An HTML Element To Clipboard-JavaScript

Change Background Color Using JavaScript

Detect Dark Mode Using JavaScript And CSS

Scroll to Top