Javascript Style How to - Change the color of a div by clicking it








Question

We would like to know how to change the color of a div by clicking it.

Answer


<!DOCTYPE html>
<html>
<head>
</head><!--from  ww w.  j a va  2 s. c o m-->
<body>
  <div style="background-color: red"
    onClick="this.style['background-color']='blue'">Demo Text 1</div>
  <div style="background-color: red"
    onClick="this.style.backgroundColor='blue'">Demo Text 2</div>
</body>
</html>

The code above is rendered as follows: