html元素
<div id="app" class="red">div>
选中元素
const app = document.querySelector('#app')
读取类名
app.className
// red
app.classList
// DOMTokenList ['red']
app.classList.value
// red
app.getAttribute('class')
// red
// 直接修改 className
app.className = 'green'
//
// 通过classList添加
app.classList.add('green')
//
// 通过setAttribute设置属性值
app.setAttribute('class', 'blue')
//
删除类名
app.className = "";
//
app.classList.remove('red')
//
app.removeAttribute('class')
//
// 存在则移除
app.classList.toggle('red')
//
// 不存在则添加
app.classList.toggle('green')
//
DOMTokenList对象
DOMTokenList
- 属性
- length 值的个数
- value 字符串形式
- 方法
- item(index)
- contains(token)
- add(token1[, token2[, ...tokenN]])
- remove(token1[, token2[, ...tokenN]])
- replace(oldToken, newToken)
- supports(token)
- toggle(token [, force])
- entries()
- forEach(callback [, thisArg])
- keys()
- values()
文档:https://developer.mozilla.org/zh-CN/docs/Web/API/DOMTokenList
综上,一共有三种方式对dom元素class属性进行读取、更新、移除操作
参考