如何从类属性中删除与模式匹配的类,但保留其他类?
上的类属性中删除以“蓝色”结尾的类
我想从所有标签示例 html
<p class="text_blue happy">this is blue text</p>
<p class="text_red nothappy">this is red text</p>
<img class="img_blue nothappy" />
这将为我提供所有以“蓝色”结尾的类的元素,
$('[class$=blue]');
如何从类属性中弹出这些匹配的类名?
I want to delete the classes that end with 'blue' from the class attribute on all tags
sample html
<p class="text_blue happy">this is blue text</p>
<p class="text_red nothappy">this is red text</p>
<img class="img_blue nothappy" />
This will give me all the elements with classes that end with 'blue'
$('[class$=blue]');
how do I pop these matched classnames off of the class attribute?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用如下正则表达式提取整个类名称:
您应该意识到的一件事是
$('[class$="blue"]')
对名为 < 的整个属性进行操作代码>类。我不对单个类名进行操作。因此,它会匹配:但是,它不会匹配:
因为类属性不以
"blue"
结尾。如果您希望它获取任何包含"blue"
的类名,无论它在类名属性中的位置如何,您都必须使用:如果您还想过滤掉包含以下内容的类名 :不是以蓝色结尾,你可以用 JS 来做到这一点,如下所示:
如果你想从对象中删除这些类名,你可以这样做:
也可以这样做,这看起来更干净,但事实并非如此t 完美地清除要删除的类名周围的额外空格:
You can pull the whole class name out with a regular expression like this:
One thing that you should realize is that
$('[class$="blue"]')
operates on the entire attribute namedclass
. I does not operate on individual class names. So, it will match:But, it will not match:
because the class attribute does not end with
"blue"
. If you want it to get any class name that contains"blue"
regardless of where it is positioned in the class name attribute, you would have to use:If you further wanted to filter out class names that did not end with blue, you could do that with JS like this:
If you want to remove these class names from the objects, you could do it like this:
It could also be done this way which seems a little cleaner, but it doesn't perfectly clean up extra whitespace around the class name it's removing:
如果您要经常这样做,您可能需要更改分配班级的方式。您可以像这样创建 HTML:
然后在 CSS 中使用
.text.blue
而不是使用.text_blue
选择器。然后你可以简单地从类中删除“蓝色”。If you're going to be doing this a lot, you might want to change how you assign classes. You can make your HTML like this:
and then instead of using a selector of
.text_blue
in your CSS, use.text.blue
instead. Then you can simply remove "blue" from the classes.