Javascript Style How to - Toggle style class on/off for css selectors








Question

We would like to know how to toggle style class on/off for css selectors.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.on {<!--   w w w.j  a v  a2  s.c o  m-->
  background-color: red;
}
</style>
</head>
<body>
  <table onclick="this.classList.toggle('on');">
    <tr>
      <td>123</td>
    </tr>
  </table>
</body>
</html>

The code above is rendered as follows: