Search notes:

Dynamically change a CSS style with javascript

The following example is an attempt at demonstrating how a CSS style can be dynamically changed with JavaScript.
<!DOCTYPE html>
<html>
<head>
  <title>Change CSS Style with JavaScript</title>
  <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
  <style type='text/css'>
    * {font-family:Verdana}
  </style>

  
  <script type="text/javascript">

    function changeColor_1() {
      var elem = document.getElementById('target_1');
      elem.style.backgroundColor = "#fa3";
    }

    function changeColor_2() {
      var elem = document.getElementById('target_2');
      elem.style['backgroundColor']='#b5f';
    }

  </script>

</head>
<body>

  Demonstration on how to change a css style with javascript.

  <form action="#">
  <div id="target_1">Pressing the first button changes my background color! Does this even work in IE?</div>
  <div id="target_2">Pressing the second button changes my background color! Does this even work in IE?</div>
  <input type="submit" value="Change top Color" onclick="changeColor_1();">
  <input type="submit" value="Change bottom Color" onclick="changeColor_2();">
  </form>

</body>
</html>
Github repository about-css, path: /javascript/change_style.html

See also

Javascript/CSS: show styles of a given element
document.styleSheets

Index