使用 JavaScript 从元素中删除 CSS 类(无 jQuery) [英] Remove CSS class from element with JavaScript (no jQuery)
本文介绍了使用 JavaScript 从元素中删除 CSS 类(无 jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我如何仅使用 JavaScript 删除元素上的类?请不要用 jQuery 给我答案,因为我不会使用它,而且我对此一无所知.
解决方案
正确且标准的方法是使用 classList
.现在在大多数现代浏览器的最新版本中得到广泛支持:
ELEMENT.classList.remove("CLASS_NAME");
remove.onclick = () =>{const el = document.querySelector('#el');如果(el.classList.contains(红色")){el.classList.remove("红色");}}
.red {背景:红色}
测试<button id='remove'>移除类</button>
文档:https://developer.mozilla.org/en/DOM/element.类列表
Could anyone let me know how to remove a class on an element using JavaScript only? Please do not give me an answer with jQuery as I can't use it, and I don't know anything about it.
解决方案
The right and standard way to do it is using classList
. It is now widely supported in the latest version of most modern browsers:
ELEMENT.classList.remove("CLASS_NAME");
remove.onclick = () => {
const el = document.querySelector('#el');
if (el.classList.contains("red")) {
el.classList.remove("red");
}
}
.red {
background: red
}
<div id='el' class="red"> Test</div>
<button id='remove'>Remove Class</button>
Documentation: https://developer.mozilla.org/en/DOM/element.classList
这篇关于使用 JavaScript 从元素中删除 CSS 类(无 jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文