不是为元素可能具有的每个类单独调用$(“#item”).removeClass(),而是可以调用一个函数来从给定元素中删除所有CSS类吗?
jQuery和原始JavaScript都可以工作。
不是为元素可能具有的每个类单独调用$(“#item”).removeClass(),而是可以调用一个函数来从给定元素中删除所有CSS类吗?
jQuery和原始JavaScript都可以工作。
当前回答
最短的方法
$('#item').removeAttr('class').attr('class', '');
其他回答
不管你信不信,我喜欢使用原生JavaScript来实现这一点!
解决方案1:className
删除所有项目的所有类别
const items = document.querySelectorAll('item');
for (let i = 0; i < items.length; i++) {
items[i].className = '';
}
仅删除第一项的所有类
const item1 = document.querySelector('item');
item1.className = '';
解决方案2:classList
// remove all class of all items
const items = [...document.querySelectorAll('.item')];
for (const item of items) {
item.classList.value = '';
}
// remove all class of the first item
const items = [...document.querySelectorAll('.item')];
for (const [i, item] of items.entries()) {
if(i === 0) {
item.classList.value = '';
}
}
// or
const item = document.querySelector('.item');
item.classList.value = '';
jQuery方式(不推荐)
$(“#item”).removeClass();$(“#item”).removeClass(“class1…classn”);
refs
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
当然
$('#item')[0].className = '';
// or
document.getElementById('item').className = '';
只需将实际DOM元素的className属性设置为“”(无)。
$('#item')[0].className = ''; // the real DOM element is at [0]
其他人说,调用removeClass就行了——我在GooglejQueryPlayground上测试了这一点:http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... 它起作用了。所以你也可以这样做:
$("#item").removeClass();
最短的方法
$('#item').removeAttr('class').attr('class', '');
让我们用这个例子。也许你想让网站的用户知道某个字段是有效的,或者需要通过更改字段的背景色来关注它。如果用户点击重置,那么代码应该只重置包含数据的字段,而不必在页面上的其他字段中循环。
此jQuery筛选器将仅删除“highlightCriteria”类具有此类的输入或选择字段。
$form.find('input,select').filter(function () {
if((!!this.value) && (!!this.name)) {
$("#"+this.id).removeClass("highlightCriteria");
}
});