Skip to content

Instantly share code, notes, and snippets.

@morbidcamel101
Created March 16, 2017 16:18
Show Gist options
  • Save morbidcamel101/8882b5f23cac0c3dff43ad0c7b765644 to your computer and use it in GitHub Desktop.
Save morbidcamel101/8882b5f23cac0c3dff43ad0c7b765644 to your computer and use it in GitHub Desktop.
JQuery style with !important
(function($) {
if ($.fn.style) {
return;
}
// Escape regex chars with \
var escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
// For those who need them (< IE 9), add support for CSS functions
var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
if (!isStyleFuncSupported) {
CSSStyleDeclaration.prototype.getPropertyValue = function(a) {
return this.getAttribute(a);
};
CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) {
this.setAttribute(styleName, value);
var priority = typeof priority != 'undefined' ? priority : '';
if (priority != '') {
// Add priority manually
var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) +
'(\\s*;)?', 'gmi');
this.cssText =
this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
}
};
CSSStyleDeclaration.prototype.removeProperty = function(a) {
return this.removeAttribute(a);
};
CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?',
'gmi');
return rule.test(this.cssText) ? 'important' : '';
}
}
// The style function
$.fn.style = function(styleName, value, priority) {
// DOM node
var node = this.get(0);
// Ensure we have a DOM node
if (typeof node == 'undefined') {
return this;
}
// CSSStyleDeclaration
var style = this.get(0).style;
// Getter/Setter
if (typeof styleName != 'undefined') {
if (typeof value != 'undefined') {
// Set style property
priority = typeof priority != 'undefined' ? priority : '';
style.setProperty(styleName, value, priority);
return this;
} else {
// Get style property
return style.getPropertyValue(styleName);
}
} else {
// Get CSSStyleDeclaration
return style;
}
};
})(jQuery);
@morbidcamel101
Copy link
Author

Use = $(this).style('color','red','important')

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