19

HTML

<div class="ativo37 and many other classes"></div>
<div class="another classes here with ativo1"></div>
<div class="here ativo9 and more two or three"></div>

JS

$("div[class^='ativo']").on("click", function(){
    $(this).removeClass("^='ativo'"); // How to achieve it?
});

What can I do instead of .removeClass("^='ativo'");?

JSFiddle

Badacadabra
  • 8,043
  • 7
  • 28
  • 49
  • Possible duplicate of [Remove all classes that begin with a certain string](https://stackoverflow.com/questions/57812/remove-all-classes-that-begin-with-a-certain-string) – Saif Jun 26 '18 at 07:55

9 Answers9

35

Without jQuery, you can use classList and startsWith:

var el = document.querySelector('div[class*="ativo"]');
for (let i = el.classList.length - 1; i >= 0; i--) {
    const className = el.classList[i];
    if (className.startsWith('ativo')) {
        el.classList.remove(className);
    }
}
str
  • 42,689
  • 17
  • 109
  • 127
33

.removeClass() accepts a function for removing classes and accepts index and old CSS value:

A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments.

You can remove the classname that starts with required name and keep the existing using:

$("div[class*='ativo']").removeClass (function (index, css) {
   return (css.match (/(^|\s)ativo\S+/g) || []).join(' ');
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • 3
    Updated relevant jsFiddle: http://jsfiddle.net/vq19cnrq/2/ Should use: `$("div[class*='ativo']")` – A. Wolff Feb 19 '15 at 14:22
24
function removeClassByPrefix(el, prefix) {
    var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
    el.className = el.className.replace(regx, '');
    return el;
}

You can use this pure Javascript solution.

void
  • 36,090
  • 8
  • 62
  • 107
  • 4
    i'm having trouble using this with classes that contain hyphens if i try to use it on a class like: `class-name` using "class" as a prefix i still end up with the "name". Any way to change the regex expression to fix this? – Ahmed Wagdi Apr 25 '16 at 21:34
  • 2
    @AhmedWagdi change the expression to: `new RegExp('\\b' + prefix + '(.*)?\\b', 'g');` – Jan Köhler Nov 14 '17 at 09:24
2

There is a problem with both @str's and @Djurdjen's answers. If you remove classes inside a forEach()-loop, you are deleting elements you are currently looping over. In Edge, for example, this might lead to className beeing null.

A better solution is to loop through the classList-elements backwards:

function removeClassesByPrefix(el, prefix)
{
    for(var i = el.classList.length - 1; i >= 0; i--) {
        if(el.classList[i].startsWith(prefix)) {
            el.classList.remove(el.classList[i]);
        }
    }
}
T Grando
  • 168
  • 4
2

I would do something like:

function removeClassStartsWith (node, className) {
   [...node.classList].forEach(v => {
      if (v.startsWith(className)) {
         node.classList.remove(v)
      }
   })
}

Usage:

// Example node: <div class="id-1"></div>

const el = document.querySelectorAll('div')[0]
removeClassStartsWith(el, 'id-')
l2aelba
  • 21,591
  • 22
  • 102
  • 138
1

I got a problem with solution above, it sometimes only removed the matched prefix from the className and not the class in its entirety. So I changed it to this

function removeClassByPrefix(el, prefix) {
    var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
    [...el.classList].forEach(className => {
        regx.test(className) && item.classList.remove(className);
    });
}
Djurdjen
  • 273
  • 2
  • 10
0
function removeClassByPrefix(el, prefix) {
    let newClassList = []
 
    el.classList.forEach(className => {
        if (className.indexOf(prefix) !== 0 ) {
            newClassList.push(className)
        }
    })
    
    el.className = newClassList.join(' ')
}
Marius Gri
  • 59
  • 3
  • It would be nice if you write some brief explanation to your code. What does the code do and how does it manage the task? – ecth Jan 11 '21 at 13:21
  • 1
    in short - it excludes all classes starting with prefix in clean way, rather than mutilation via regexp Line by line: 1. defines a method; 2. creates a local array; 4. loops through class list (browsers native class list) of DOM element that comes from argument named "el"; 5. checks if class name in the cycle does not start with prefix that comes from argument named "prefix"; 6. appends a valid class name to newClassList; 10. joins class list array into a string separated by spaces and sets it to the mentioned DOM element; – Marius Gri Jan 12 '21 at 14:42
0

This approach allows to remove css classes by any string-filter without the jquery-prerequisite.

node.classList.remove(
    ...Array.from(node.classList.entries())
       .map(([,c]) => c)
       .filter(c => c.startsWith('prefix')));

What it does is, using the entries() iterator to create an array from the classlist entries. These are in the format [index, classname]. Now I can comfortably first map them to just the classname and then use all kind of array functions (like filter in this case) to find the correct set of classes.

  • 2
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 15 '21 at 06:42
0

I write this function to remove given class name from HTMLElement using 'startsWith()'

export function removeClassStartingWith(currentEl, currentClassName){
  currentEl.classList.forEach((curr, index) => {
    if(curr.startsWith(currentClassName)){
      const currentClass = currentEl.classList[index];
      currentEl.classList.remove(currentClass);
      return true;
    }else{
      return false;
    }
  });
}