Skip to content

Instantly share code, notes, and snippets.

@tzi
Last active March 21, 2023 08:54
Show Gist options
  • Save tzi/2953155 to your computer and use it in GitHub Desktop.
Save tzi/2953155 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/200/300" ) !important' );
// Modern browser
} else {
element.setAttribute( 'style', 'background-image: url( "http://placekitten.com/200/300" ) !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>
@mangelozzi
Copy link

mangelozzi commented Aug 25, 2022

How to set the !important css property using pure Javascript (element.dataset.color)
Any solution for the method like below???
el.style.backgroundColor = element.dataset.color
am trying this
el.style.backgroundColor = element.dataset.color + '!important'
Same trick works fine with + '%' , Whats wrong with + '!important'

The !important tag can't be concatenated onto the end of the string the same way % does, it's not a unit.

Its not that far fetched, since !important is concatenated onto the end of the string in style sheets, even though it's not a unit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment