删除以特定字符串开头的所有类 [英] Remove all classes that begin with a certain string

查看:188
本文介绍了删除以特定字符串开头的所有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div id =a,可以有多个类附加到它,从几个组。每个组都有一个特定的前缀。在javascript中,我不知道组中的哪个类是在div。我想要能够清除所有类与给定的前缀,然后添加一个新的。如果我想删除所有以bg开头的类,我该怎么做?这样的东西,但实际上是工作:

I have a div with id="a" that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works:

$("#a").removeClass("bg*");


推荐答案

使用jQuery,实际的DOM元素处于索引零,这应该工作

With jQuery, the actual DOM element is at index zero, this should work

$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');

这篇关于删除以特定字符串开头的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆