如何从所有元素中删除特定的类? [英] How to remove a specific class from all elements?

查看:71
本文介绍了如何从所有元素中删除特定的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从页面元素中删除给定的类?

How do I remove a given class from the page elements?

示例:

<div class="fan light"> ... </div>
<div class="light"> ... </div>
<h3 class="seahorse light"> SomeHeading </h3>

我想从页面的所有元素中删除类light

I want to drop the class light from all elements of the page!

如何使用jquery或javascript做到这一点?

How do I do that using jquery or javascript?

推荐答案

只需找到要做具有该类的所有元素,然后将其删除:

Just find all the elements that do have the class, and remove it:

$(".light").removeClass("light");

使用普通JavaScript:

With plain JavaScript:

var lights = document.getElementsByClassName("light");
while (lights.length)
    lights[0].className = lights[0].className.replace(/\blight\b/g, "");

(依赖于支持.getElementsByClassName()的浏览器.)请注意,循环看起来有些奇怪,始终在元素列表的元素0上运行.这是因为从.getElementsByClassName()之类的API返回的列表是实时—它们进行更改以反映DOM中的更改.从某个元素中删除一个类后,该类将不再位于具有该类名称的元素列表中.因此,通过从列表中的第一个元素中删除类,该元素将消失.最终,该列表将为空. (我一直以为这是一种奇怪的行为,公然违反了最少惊奇的原则,但是你去了.)

(That relies on the browser supporting .getElementsByClassName().) Note that the loop looks a little weird, always operating on element 0 of the element list. That's because the lists returned from APIs like .getElementsByClassName() are live — they change to reflect changes in the DOM. When a class is removed from an element, it's no longer in the list of elements with that class name. Thus by removing the class from the first element in the list, that element goes away. Eventually the list will be empty. (I've always thought that this was a bizarre behavior that flagrantly violates the principle of least surprise, but there you go.)

最后,在评论中指出,较新的浏览器(IE10 +)支持称为.classList的DOM元素属性.这是一个类名列表,并且它支持一些方便的方法.特别是:

Finally it's pointed out in a comment that newer browsers (IE10+) support a DOM element property called .classList. It's a list of class names, plus it supports some handy methods. In particular:

var lights = document.getElementsByClassName("light");
while (lights.length)
    lights[0].classList.remove("light");

这篇关于如何从所有元素中删除特定的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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