html element
<div id="app" class="red"></div>
selected element
const app = document.querySelector('#app')
read class name
app.className
// red
app.classList
// DOMTokenList ['red']
app.classList.value
// red
app.getAttribute('class')
// red
Modify class name
// 直接修改 className
app.className = 'green'
// <div id="app" class="green"></div>
// 通过classList添加
app.classList.add('green')
// <div id="app" class="red green"></div>
// 通过setAttribute设置属性值
app.setAttribute('class', 'blue')
// <div id="app" class="blue"></div>
delete class name
app.className = "";
// <div id="app" class=""></div>
app.classList.remove('red')
// <div id="app" class=""></div>
app.removeAttribute('class')
// <div id="app"></div>
switch class name
// 存在则移除
app.classList.toggle('red')
// <div id="app" class=""></div>
// 不存在则添加
app.classList.toggle('green')
// <div id="app" class="red green"></div>
DOMTokenList object
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()
Documentation: https://developer.mozilla.org/zh-CN/docs/Web/API/DOMTokenList
In summary, there are three ways to read, update and remove the class attribute of the dom element
reference