JavaScript – Change Font Color of HTML Element
To change the font color of a HTML Element using JavaScript, get reference to this HTML element, and assign required color value to the element.style.color
property.
In the following example, we will change the font color of HTML Element with id "myElement"
to the color "#FF0000"
, in JavaScript, using element.style.color
property.
example.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#myElement {
border:1px solid #CCC;
width:100px;
height:100px;
}
</style>
<meta charset="utf-8">
</head>
<body>
<h2>Change Font Color of HTML Element in JavaScript</h2>
<div id="myElement">Hello World!</div>
<br>
<button type="button" onclick="changeStyle()">Click Me</button>
<script>
function changeStyle(){
var element = document.getElementById("myElement");
element.style.color = "#FF0000";
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to change the font color of a HTML Element using JavaScript.