0

Is there a simple way to remove a class from an element when I don't know the exact class name (only a prefix)?

At first this might sound strange so I give an example to clarify: a Bootstrap button may have btn-primary xor btn-success xor btn-danger xor ... applied. I want to remove this class (whichever it is) and apply a new one.

Currently I have:

let btnClasses = [ 'btn-primary', 'btn-success', ... ];
$.each(btnClasses, function(i, x) {
    $(myElem).removeClass(x);
});

I'd love to have something alike:

$(myElem).removeClass('btn-*');

Is there a built-in way to do so?

D.R.
  • 18,900
  • 20
  • 82
  • 181

1 Answers1

1

You could write your own plugin for jQuery. It would be named differently but it's one way.

$.fn.removeClassRegex = function (pattern) {
  var element = $(this);
  var classNames = element.attr('class').split(' ');
  $(classNames).each(function (key, value) {
    if (value.match(pattern)) {
      element.removeClass(value);
    }
  });
}

$('div').removeClassRegex('test-[a-z]');
console.log($('div').attr('class'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test-bar foo">
</div>
Cjmarkham
  • 9,057
  • 4
  • 47
  • 80
  • A good alternative - thank you for your effort - upvoted! Still, personally, I'm going to use the built-in way as described in the linked duplicate. – D.R. Oct 09 '16 at 19:37
  • Yeh, just read that answer and it is a much better solution – Cjmarkham Oct 09 '16 at 19:38