前言
之前为了操纵DOM元素class列表,经常会引入jQuery之类的库。其实html5的classList API还是非常方便的,而且兼容性也不错。
API用法
假设我们有这样一个DOM元素
获取DOM元素
1
| const el = document.querySelector("#el");
|
然后你可以用classList方法操纵该元素上所有的类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| el.classList.add("open");
el.classList.add("this", "little", "piggy"); let classes = ["is-message", "is-warning"]; el.classList.add(...classes);
el.classList.remove("open");
el.classList.remove("this", "little", "piggy");
el.classList.forEach(className => { console.log(className); }); for (let className of $0.classList) { console.log(className); }
el.classList.length;
el.classList.replace("is-big", "is-small");
el.classList.toggle("open");
el.classList.toggle("open", false);
el.classList.toggle("open", true);
el.classList.contains("open");
el.classList.item(0); el.classList.item(1); el.classList.item(2); el.classList[1];
|
兼容性