To start off, let's use this example DOM:
<body> <p class="content"> Hello World! </p> </body>
The text we want to change is the paragraph element that says "Hello World!".
To start, we will need to first query for the element.
document.querySelector() function to do this, and pass in the CSS selector for the element we want to change.
const element = document.querySelector(".content");
Now that we got the element, we can proceed to change the color of the text.
To change the color of the text, we'll be setting its
style.color property. This is a built-in property for HTML elements that represents the color of the text.
All we need to do is change this property to the color that we want, and the browser will take care of the rest.
Here's how to change the color to
const element = document.querySelector(".content"); element.style.color = "red";
It also supports hexadecimal colors, like
By manipulating the
style.color property, we can both read and update the color of the element.
Hopefully, this has been useful for you. Thanks for reading!
Leave us a message!