懶人包系列。
新增或移除 ClassList
備註:既然 classList 都叫 List 了,就代表可以想成是一個陣列,他不會把整筆 Class 覆寫掉。
新增單個
HTML:
1 | <div>yoyoyo</div> |
JavaScript:
1 | const element = document.getElementsByTagName('div')[0] |
Output:
1 | <div class="block">yoyoyo</div> |

新增多個
HTML:
1 | <div>yoyoyo</div> |
JavaScript:
1 | const element = document.getElementsByTagName('div')[0] |
Output:
1 | <div class="block inline-block">yoyoyo</div> |

移除單個
HTML:
1 | <div class="block">yoyoyo</div> |
JavaScript:
1 | const element = document.querySelector('.block') |
Output:
1 | <div>yoyoyo</div> |
移除多個
HTML:
1 | <div class="block inline-block">yoyoyo</div> |
JavaScript:
1 | const element = document.querySelector('.block') |
Output:
1 | <div>yoyoyo</div> |
切換 Class
HTML:
1 | <div class="block inline-block">yoyoyo</div> |
JavaScript:
1 | const element = document.querySelector('.block') |
Output:

把整個 Class 覆寫掉 ClassName
應該不常用,但可以知道一下。
範例一
HTML:
1 | <div class="block">yoyoyo</div> |
JavaScript:
1 | const element = document.querySelector('.block') |
Output:
1 | <div class="override-backgroud">yoyoyo</div> |

範例二
1 | <div class="block">yoyoyo</div> |
JavaScript:
1 | const element = document.querySelector('.block') |
Output:
1 | <div class="block override-backgroud">yoyoyo</div> |
