Skip to content

Instantly share code, notes, and snippets.

@carloscabo
Last active April 4, 2020 23:02
Show Gist options
  • Select an option

  • Save carloscabo/e0374676c614dd6e6ea19ad4b9ecf9a4 to your computer and use it in GitHub Desktop.

Select an option

Save carloscabo/e0374676c614dd6e6ea19ad4b9ecf9a4 to your computer and use it in GitHub Desktop.
/*
Add / remove prefixes to DOM element classes. Requieres JQuery.
https://gist.github.com/carloscabo/e0374676c614dd6e6ea19ad4b9ecf9a4
by Carlos Cabo 2016. MIT License.
How it works:
1. Loops over the group of elements
2. For each element if it has any class that matches the regex:
a. If the prefix is NOT present -> adds
b. If the prefix IS present -> removes
$jquery_selector, conatining group of elements where replacement will be done
regex, refired to the classname, all classes matching this selector in the group of elements will be un/prefixed
prefix, string that will be added / removed from matching classes
add, true = add prefix ( default value)
flase = remove prefix
Adding 'pre-' to all classnames matched in regex:
addRemoveClassPrefix(
$('#imgs-slider, #imgs-slider [class^=swiper]'), // JQuery selector: Group of elements where to be executed
/^swiper/, // RegEx: All classNames starting with 'swiper'
'pre-' // Add this prefix
);
Removing 'pre-' to all classnames matched in regex:
addRemoveClassPrefix(
$('[class^=pre-swiper]'), // JQuery selector: Group of elements where to be executed
/^pre-swiper/, // RegEx: All classNames starting with 'swiper'
'pre-' // Add this prefix
);
*/
function addRemoveClassPrefix( $jquery_selector, regex, prefix ) {
if ($jquery_selector.length) {
$jquery_selector.each( function(idx, el) {
var
$el = $(el),
classes = $el.attr('class').split(' '),
new_class;
for (var i = 0; i < classes.length; i++) {
if (regex.test( classes[i] )) {
new_class = ( classes[i].indexOf( prefix ) === 0 ) ? classes[i].replace( prefix, '') : prefix+classes[i] ;
$el.addClass( new_class ).removeClass( classes[i] );
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment