How to remove a class that starts with...?
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.
.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
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);
}
}