jQuery addClass example
Change class name on click in jQuery
HTML
<div>
This demo overrides <b>!important</b> styles set in the page's <style> tag.
</div>
<button>Click Me</button>
<br/><br/>
<div id="elem">
I should be 100px tall.
</div>
<br/><br/>
<div id='another'>
I should be visible with a fishy color.
</div>
<br/>
<div class='item'>I Should be red.</div>
<div class='item'>I Should be red.</div>
CSS
#elem {
height: 10px !important;
background-color: cornsilk;
display: inline-block;
}
#another {
background-color: none !important;
display: none !important;
}
.item {
color: blue !important;
}
div {
padding: 10px;
}
button {
margin: 10px;
}
JavaScript
/**
* Sets a CSS style on the selected element(s) with !important priority.
*
* @param {string|Object<string, string>} name
* @param {string|undefined} value
* @return {!Element}
*/
jQuery.fn.cssImportant = function(name, value) {
const $this = this;
const applyStyles = (n, v) => {
// Loop over each element in the selector setting styles.
const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
return m1 + "-" + upper.toLowerCase() + m2;
});
$this.each(function(){
this.style.setProperty(dashedName, v, 'important');
});
};
// If called with a single parameter that is an object,
// Loop over the entries in the object and apply those styles.
if(jQuery.isPlainObject(name) && value === undefined){
for(const [n, v] of Object.entries(name)){
applyStyles(n, v);
}
} else {
// Otherwise called with style name and value.
applyStyles(name, value);
}
// This is required for making jQuery plugin calls chainable.
return $this;
};
$(function(){
$('button').on('click', (e) => {
// Call the new plugin:
$('#elem').cssImportant('height', '100px');
// Call with an object and camelCased style names:
$('#another').cssImportant({'backgroundColor': 'salmon', 'display': 'block'});
// Call on multiple items:
$('.item').cssImportant('color', 'red');
});
});