3

I have the following HTML:

<div class="cols someclass"></div> <!--like this cols1, cols2, etc..-->
<div class="columns someclass"></div> <!--like this columns1, columns2, etc...-->
<div class="col-1 someclass"></div> <!--like this col-2, col-3,etc...-->
<div class="column-1 someclass"></div> <!--like this column-2, column-3, etc...-->

How to remove all classes starting with "col"?

Fabrício Matté
  • 65,581
  • 23
  • 120
  • 159
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187
  • Answered here: http://stackoverflow.com/questions/57812/remove-all-classes-that-begin-with-a-certain-string – sarink May 01 '14 at 21:32

1 Answers1

6

I believe there is no jQuery magic for this, so here's my solution:

$('[class*=col]').each(function() {
    this.className = $.grep(this.className.split(' '), function(el) {
        return !/^col/.test(el);
    }).join(' ');
});

Fiddle

Basically, it selects elements that have col in their classes and iterate over them, iterating over their classes and removing those that begin with col.

Or without regex:

$('[class*=col]').each(function() {
    this.className = $.grep(this.className.split(' '), function(cl) {
        return cl.lastIndexOf('col', 0);
    }).join(' ');
});

Fiddle

Using a modified version of this answer. lastIndexOf will return 0 if the class starts with col which is a falsy value and thus grep will remove it. If the class does not begin with col, then -1 is returned which is a truthy value. You can use return cl.lastIndexOf('col', 0) !== 0; for a bit extra readability as well.

Or with regex only:

$('[class*=col]').each(function() {
    this.className = this.className.replace(/(^| )col[^ ]*/g, '');
});

Fiddle

Matches col at beginning of the string or after a space, removes it together with all leading characters up to another space or end of the string.


Referece

  • jQuery.grep - Finds the elements of an array which satisfy a filter function. The original array is not affected.
  • element.className - gets and sets the value of the class attribute of the specified element.

Of course, this selector is not optimal - if an element has foocol the $('[class*=col]') will select it, but the $.grep/regex will not remove it as it does not begin with col. I can't think of any better selector (there's no attribute selector to select a value beginning with a partial string in a space-separated list AFAIK), nevertheless this should suffice just fine.

Community
  • 1
  • 1
Fabrício Matté
  • 65,581
  • 23
  • 120
  • 159