不是为元素可能具有的每个类单独调用$(“#item”).removeClass(),而是可以调用一个函数来从给定元素中删除所有CSS类吗?

jQuery和原始JavaScript都可以工作。


当前回答

只需将实际DOM元素的className属性设置为“”(无)。

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

其他人说,调用removeClass就行了——我在GooglejQueryPlayground上测试了这一点:http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... 它起作用了。所以你也可以这样做:

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

其他回答

只需将实际DOM元素的className属性设置为“”(无)。

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

其他人说,调用removeClass就行了——我在GooglejQueryPlayground上测试了这一点:http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... 它起作用了。所以你也可以这样做:

$("#item").removeClass();
$('#elm').removeAttr('class');

属性“class”将不再出现在“elm”中。

让我们用这个例子。也许你想让网站的用户知道某个字段是有效的,或者需要通过更改字段的背景色来关注它。如果用户点击重置,那么代码应该只重置包含数据的字段,而不必在页面上的其他字段中循环。

此jQuery筛选器将仅删除“highlightCriteria”类具有此类的输入或选择字段。

$form.find('input,select').filter(function () {
    if((!!this.value) && (!!this.name)) {
        $("#"+this.id).removeClass("highlightCriteria");
    }
});

当然

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

由于并非所有版本的jQuery都是相同的,因此您可能会遇到与我相同的问题,这意味着调用$(“#item”).removeClass();实际上并没有删除该类(可能是一个bug)。

更可靠的方法是简单地使用原始JavaScript并完全删除class属性。

document.getElementById("item").removeAttribute("class");