Javascript Style How to - Change text color








Question

We would like to know how to change text color.

Answer


<!DOCTYPE html>
<html>
<head>
</head><!-- w w  w  .  jav  a2  s .  c o  m-->
<body>
  <p id="pg">Hi, this is a string of text.</p>
  <button type="button" onclick="change()">Click Me!</button>
  <script type='text/javascript'>
var colors = ['#3498db', '#e67e22', '#16a085', '#f39c12', '#2c3e50', '#7f8c8d', '#2980b9'];
var i = 0;
function change() {
    var x = document.getElementById("pg");
    x.style.color = colors[i++ % colors.length];
}

</script>
</body>
</html>

The code above is rendered as follows: