Rich Holt
Rich Holt

Reputation: 31

How to find and replace the prefix of a classname with jQuery?

I have a bunch of class names like md:block and sm:flex

I need to:

  1. Find all classes that begin with 'md' or 'sm'.
  2. Append '-panel' after each 'md' and 'sm'.
  3. End up with md-panel:block and sm-panel:flex.

First attempt in comments: https://stackoverflow.com/a/61035473/4019931

Second attempt:

/*
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] );
        }
      }
    });
  }
}

I found this (https://gist.github.com/carloscabo/e0374676c614dd6e6ea19ad4b9ecf9a4) which almost does what I want. But I have 3 issues I can't figure out.

  1. How to set the regex to /*md/ without it turning into a comment in the code.
  2. How to set multiple things in the regex. /*sm/*md/ ?
  3. How to change it so that it splits in the middle of the class name and adds the first part + prefix + last part. I tried this:

    new_class = ( classes[i].indexOf( prefix ) === 0 ) ? classes[i].split('-panel:').join(':') : classes[i].split(':').join('-panel:');

I need it to turn all 'md:value' to 'md-panel:value' and vice versa. Any help would be greatly appreciated.

Upvotes: 1

Views: 989

Answers (2)

Rich Holt
Rich Holt

Reputation: 31

Figured one solution :)

$('[class*="sm:"], [class*="md:"]').attr("class", function(i, val) {
  return val.split(":").join("-panel:");
});

Upvotes: 2

MHon Romero
MHon Romero

Reputation: 9

Use hasclass and replace

$('this').hasClass('md').replace('md-panel')

Upvotes: -1

Related Questions