用 DOM 改變元素的 Class

懶人包系列。

新增或移除 ClassList

備註:既然 classList 都叫 List 了,就代表可以想成是一個陣列,他不會把整筆 Class 覆寫掉。

新增單個

HTML:

1
<div>yoyoyo</div>

JavaScript:

1
2
const element = document.getElementsByTagName('div')[0]
element.classList.add('block')

Output:

1
<div class="block">yoyoyo</div>

class-list-01

新增多個

HTML:

1
<div>yoyoyo</div>

JavaScript:

1
2
const element = document.getElementsByTagName('div')[0]
element.classList.add('block', 'inline-block')

Output:

1
<div class="block inline-block">yoyoyo</div>

class-list-02

移除單個

HTML:

1
<div class="block">yoyoyo</div>

JavaScript:

1
2
const element = document.querySelector('.block')
element.classList.remove('block')

Output:

1
<div>yoyoyo</div>

移除多個

HTML:

1
<div class="block inline-block">yoyoyo</div>

JavaScript:

1
2
const element = document.querySelector('.block')
element.classList.remove('inline-block', 'block')

Output:

1
<div>yoyoyo</div>

切換 Class

HTML:

1
2
<div class="block inline-block">yoyoyo</div>
<button>Toggle Class</button>

JavaScript:

1
2
3
4
5
const element = document.querySelector('.block')
document.querySelector('button').addEventListener('click',
// 按下按鈕時,切換 class
() => element.classList.toggle('inline-block')
)

Output:

toggle

把整個 Class 覆寫掉 ClassName

應該不常用,但可以知道一下。

範例一

HTML:

1
<div class="block">yoyoyo</div>

JavaScript:

1
2
const element = document.querySelector('.block')
element.className = 'override-backgroud'

Output:

1
<div class="override-backgroud">yoyoyo</div>

class-name-01

範例二

1
<div class="block">yoyoyo</div>

JavaScript:

1
2
const element = document.querySelector('.block')
element.className = 'block override-backgroud'

Output:

1
<div class="block override-backgroud">yoyoyo</div>

class-name-02

用 DOM 改變元素內容 用 DOM 改變元素的 CSS
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×