假设您在DOM中有一个元素:
<div id="el"></div>
获取对该DOM元素的引用:
const el = document.querySelector("#el");
然后,您可以使用classList
方法操作该元素上的classList
。
// Add a class
el.classList.add("open");
// Add many classes
el.classList.add("this", "little", "piggy");
let classes = ["is-message", "is-warning"];
el.classList.add(...classes);
// Remove a class
el.classList.remove("open");
// Remove multiple classes
el.classList.remove("this", "little", "piggy");
// Loop over each class
el.classList; // DOMTokenList (pretty much an array)
el.classList.forEach(className => {
// don't use "class" as that's a reserved word
console.log(className);
});
for (let className of $0.classList) {
console.log(className);
}
el.classList.length; // integer of how many classes there are
// Replace a class (replaces first with second)
el.classList.replace("is-big", "is-small");
// Toggle a class (if it's there, remove it, if it's not there, add it)
el.classList.toggle("open");
// Remove the class
el.classList.toggle("open", false);
// Add the class
el.classList.toggle("open", true);
// Add the class with logic
el.classList.toggle("raining", weather === "raining");
// Check if element has class (returns true or false)
el.classList.contains("open");
// Look at individual classes <div class="hot dog">
el.classList.item(0); // hot
el.classList.item(1); // dog
el.classList.item(2); // null
el.classList[1]; // dog
浏览器支持
该浏览器支持数据来自Caniuse ,其更多信息。 数字表示浏览器支持该版本及更高版本的功能。
桌面
铬 | 火狐浏览器 | IE浏览器 | 边缘 | 苹果浏览器 |
---|---|---|---|---|
28 | 26 | 11 | 12 | 7 |
手机/平板电脑
Android Chrome浏览器 | Android Firefox | 安卓系统 | iOS Safari |
---|---|---|---|
81 | 68 | 4.4 | 7.0-7.1 |
翻译自: https://css-tricks.com/snippets/javascript/the-classlist-api/