如何使用jQuery / JavaScript删除所有CSS类?

本文翻译自:How to remove all CSS classes using jQuery/JavaScript?

Instead of individually calling $("#item").removeClass() for every single class an element might have, is there a single function which can be called which removes all CSS classes from the given element? 而不是为元素可能拥有的每个单独单独调用$("#item").removeClass() ,是否有一个可以调用的函数从给定元素中删除所有CSS类?

Both jQuery and raw JavaScript will work. jQuery和原始JavaScript都可以工作。


#1楼

参考:https://stackoom.com/question/5yhZ/如何使用jQuery-JavaScript删除所有CSS类


#2楼

Of course. 当然。

$('#item')[0].className = '';
// or
document.getElementById('item').className = '';

#3楼

Just set the className attribute of the real DOM element to '' (nothing). 只需将真实DOM元素的className属性设置为'' (无)。

$('#item')[0].className = ''; // the real DOM element is at [0]

Edit: Other people have said that just calling removeClass works - I tested this with the Google JQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. 编辑:其他人说只是调用removeClass工作 - 我用Google JQuery Playground测试了这个: httpremoveClass ...它的工作原理。 So you can also do it this way: 所以你也可以这样做:

$("#item").removeClass();

#4楼

$("#item").removeClass();

Calling removeClass with no parameters will remove all of the item's classes. 调用不带参数的removeClass将删除所有项的类。


You can also use (but is not necessarily recommended, the correct way is the one above): 您也可以使用(但不一定推荐, 正确的方法是上面的方法):

$("#item").removeAttr('class');
$("#item").attr('class', '');
$('#item')[0].className = '';

If you didn't have jQuery, then this would be pretty much your only option: 如果你没有jQuery,那么这将是你唯一的选择:

document.getElementById('item').className = '';

#5楼

Hang on, doesn't removeClass() default to removing all classes if nothing specific is specified? 如果没有指定任何特定内容,请挂起,不删除Class()默认删除所有类? So 所以

$("#item").removeClass();

will do it on its own... 将自己做...


#6楼

最短的方法

$('#item').removeAttr('class').attr('class', '');
发布了0 篇原创文章 · 获赞 75 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/w36680130/article/details/105450652