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?
});
我可以做什么而不是.removeClass("^='ativo'");
?
答案 0 :(得分:14)
.removeClass()
接受一个删除类的函数,并接受索引和旧的CSS值:
一个函数,返回一个或多个要删除的空格分隔的类名。接收集合中元素的索引位置和旧类值作为参数。
您可以删除以所需名称开头的类名,并使用以下内容保留现有名称:
$("div[class*='ativo']").removeClass (function (index, css) {
return (css.match (/(^|\s)ativo\S+/g) || []).join(' ');
});
<强> Working Demo 强>
答案 1 :(得分:14)
function removeClassByPrefix(el, prefix) {
var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
el.className = el.className.replace(regx, '');
return el;
}
您可以使用此纯Javascript 解决方案。
答案 2 :(得分:2)
没有jQuery,您可以使用classList
和startsWith
:
var el = document.querySelector('div[class^="ativo"]');
el.classList.forEach(className => {
if (className.startsWith('ativo')) {
el.classList.remove(className);
}
});
答案 3 :(得分:1)
上面的解决方案存在问题,有时只会从className中删除匹配的前缀,而不是整个类。所以我把它改成了这个
For
答案 4 :(得分:1)
@str和@Djurdjen的答案都存在问题。如果在forEach()
循环中删除类,则将删除当前正在循环的元素。例如,在Edge中,这可能会导致className
成为null
的蜜蜂。
更好的解决方案是向后循环遍历classList
个元素:
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]);
}
}
}
答案 5 :(得分:0)
function removeClassByPrefix(el, prefix) {
let newClassList = []
el.classList.forEach(className => {
if (className.indexOf(prefix) !== 0 ) {
newClassList.push(className)
}
})
el.className = newClassList.join(' ')
}
答案 6 :(得分:0)
我会这样做:
function removeClassStartsWith (node, className) {
[...node.classList].forEach(v => {
if (v.startsWith(className)) {
node.classList.remove(v)
}
})
}
用法:
// Example node: <div class="id-1"></div>
const el = document.querySelectorAll('div')[0]
removeClassStartsWith(el, 'id-')