user4227915
user4227915

Reputation:

How to remove a class that starts with...?

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

Upvotes: 20

Views: 29221

Answers (9)

C Alonso C Ortega
C Alonso C Ortega

Reputation: 105

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;
    }
  });
}

Upvotes: 1

Simon Bethke
Simon Bethke

Reputation: 21

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.

Upvotes: 2

l2aelba
l2aelba

Reputation: 22167

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-')

Upvotes: 2

Marius Gri
Marius Gri

Reputation: 59

function removeClassByPrefix(el, prefix) {
    let newClassList = []
 
    el.classList.forEach(className => {
        if (className.indexOf(prefix) !== 0 ) {
            newClassList.push(className)
        }
    })
    
    el.className = newClassList.join(' ')
}

Upvotes: 0

str
str

Reputation: 44969

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);
    }
}

Upvotes: 38

T Grando
T Grando

Reputation: 168

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

Upvotes: 2

Djurdjen
Djurdjen

Reputation: 283

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);
    });
}

Upvotes: 1

void
void

Reputation: 36703

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.

Upvotes: 24

Milind Anantwar
Milind Anantwar

Reputation: 82241

.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

Upvotes: 36

Related Questions