1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】HTML 要素のクラスの追加・削除

Last updated at Posted at 2020-09-13

JavaScriptでHTML要素のクラスを追加・削除するにはclassListを使用する。
#クラスの追加
■書き方

[取得した要素].classList.add('クラス名');

#クラスの削除
■書き方

[取得した要素].classList.remove('クラス名');

#クラスの有無で追加or削除
■書き方

[取得した要素].classList.toggle('クラス名');

#サンプルコード

example.html
<div id="example" class="a"></div>
example.js

// 要素を取得
var example = document.getElementById('example');

// 'b' を追加
example.classList.add('b');
// 結果 <div id="example" class="a b"></div>

// 'a' を削除
example.classList.remove('a');
// 結果 <div id="example" class="b"></div>

// toggle 'c' 
example.classList.toggle('c');
// 結果 <div id="example" class="b c"></div>

// toggle 'c' 
example.classList.toggle('c');
// 結果 <div id="example" class="b"></div>

#参照
MDN web docs

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?