Skip to content

Instantly share code, notes, and snippets.

@JARVIS-AI
Forked from tzi/important.css
Created March 15, 2021 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JARVIS-AI/b04bd7da23fe0ec1f0f69520d3e682c3 to your computer and use it in GitHub Desktop.
Save JARVIS-AI/b04bd7da23fe0ec1f0f69520d3e682c3 to your computer and use it in GitHub Desktop.
How to set an !important css property in javascript

If you want to try it, go here

To set a CSS inline style as an !important one in javascript, you have to use the element.setAttribute() method.

But you can't use this one in old IE to set style. There is a specific syntax ;)

.test {
height: 139px;
width: 96px
}
(function(){
var elements = document.getElementsByTagName( 'div' );
element = elements[ 0 ];
// Specific old IE
if ( document.all ) {
element.style.setAttribute( 'cssText', 'background-image: url( "http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg" ) !important' );
// Modern browser
} else {
element.setAttribute( 'style', 'background-image: url( "http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg" ) !important' );
}
})();
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>How to set an !important css property in javascript</title>
<link href="important.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="test">Miaaou</div>
<script type="text/javascript" src="important.js"></script>
<body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment