Add a "myStyle" class to an element:
const list = element.classList;
list.add("myStyle");
Try it Yourself »
Remove the "myStyle" class from an element:
const list = element.classList;
list.remove("myStyle");
Try it Yourself »
Toggle "myStyle" on and off:
const list = element.classList;
list.toggle("myStyle");
Try it Yourself »
More examples below.
The add()
method adds one (or more) tokens to a DOMTokenList.
domtokenlist.add(token)
Parameter | Description |
token | Required. The token(s) to add to the list. |
NONE |
Add multiple classes to the an element:
const list = element.classList;
list.add("myStyle", "anotherClass", "thirdClass");
Try it Yourself »
Get number of class tokens for an element:
const list = element.classList;
let numb = list.length;
Try it Yourself »
Get the class tokens of the "myDIV" element:
const list = document.getElementById("myDIV").classList;
Try it Yourself »
Get the first class token of an element:
let className = element.classList.item(0);
Try it Yourself »
Does an an element has a "myStyle" class token?
let x = element.classList.contains("myStyle");
Try it Yourself »
Remove "anotherClass" if an element has a "myStyle" class token.
if (element.classList.contains("mystyle")) {
element.classList.remove("anotherClass");
}
Try it Yourself »
domtokenlist.add()
is a DOM Level 4 (2015) feature.
It is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
domtokenlist.add()
is not supported in Internet Explorer 11 (or earlier).
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!