Javascript Style How to - Set a CSS property with the !important flag via the DOM








Question

We would like to know how to set a CSS property with the !important flag via the DOM.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
#test {<!--from   w  w  w .java2 s .  c o  m-->
  padding: 1em;
  font-size: 50px;
  font-weight: bold;
  color: red !important;
}
</style>
</head>
<body>
  <div id="test">This is a test</div>
  <script type='text/javascript'>
var elem = document.getElementById('test');
elem.style.setProperty( 'color', 'green', 'important' );

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

The code above is rendered as follows: