Pete Pete - 1 year ago 85
HTML Question

Changing color of text on click HTML

I'm currently learning HTML. I have to do an exercice where a text must change back and forth from red to green.
The code I have is below but doesn't seem to work. Any help would be appreciated.

.red { color : #FF0000 }
.green {color : #00FF00; }
<script type='text/javascript'>
function f(){
if (value == 1) {
document.getElementById("txt").className = "green";
value = 0
else if (value == 0) {
value = 1
<p id='i1'>This is <em> special </em> <span id="txt" class='red'>text</span>.</p>
<p id="click" onclick='f();'>Click to change the colour of text</p>

Answer Source

Don't set any value. Check directly txt class.

function f(){
  var txt = document.getElementById("txt");

  if (txt.className == 'green') {
   txt.className = "red";
  else {
    txt.className = "green";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download