Created
March 16, 2017 16:18
-
-
Save morbidcamel101/8882b5f23cac0c3dff43ad0c7b765644 to your computer and use it in GitHub Desktop.
JQuery style with !important
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use = $(this).style('color','red','important')