jQuery 要素にクラス、idを追加、削除する方法

class、idは本来、htmlで定義しますが
何らかの動作時にのみclass、idを追加したい場面が多々あります。
そんな時に使える、jQueryでのclass、idの追加削除方法をまとめました。
classの追加「addClass」
$(‘要素’).addClass(‘クラス名’);
(例)headerに「fixed」というclassを追加する場合
|
1 |
$('header').addClass('fixed'); |
classは複数追加することも出来ます。
$(‘要素’).addClass(‘クラス名 クラス名 クラス名’)
classの削除「removeClass」
$(‘要素’).removeClass(‘クラス名’);
(例)headerから「fixed」というclassを削除する場合
|
1 |
$('header').removeClass('fixed'); |
【応用】スクロールが100に達したらheaderを固定する
|
1 2 3 4 5 6 7 |
$(window).scroll(function () { if ($(this).scrollTop() > 100) { $('header').addClass('fixed'); } else { $('header').removeClass('fixed'); } }); |
|
1 2 3 4 5 |
.fixed { position: fixed; top: 0px; z-index: 999; } |
classがあれば削除、なければ追加「toggleClass」
$(‘要素’).toggleClass(‘クラス名’);
(例)headerに「fixed」というclassがあれば削除、なければ追加する場合
|
1 |
$('header').toggleClass('fixed'); |
idの追加「attr」
$(‘要素’).attr(‘id’,’id名’);
(例)headerに「fixed」というidを追加する場合
|
1 |
$('header').attr('id','fixed'); |
idの削除「removeAttr」
$(‘要素’).removeAttr(‘id’);
(例)headerからidを削除する場合
$(‘header’).removeAttr(‘id’);
スクロール時、PC表示とSP表示時にcssプロパティを変えたい場合など、
使える場面が沢山あるので是非覚えておきましょう!
![MARKLEAPS[マークリープス]](https://markleaps.com/blog/wp-content/themes/mkl/images/00_logo.png)
![[JavaScript] 特定の曜日にだけ要素を表示する方法](https://markleaps.com/blog/wp-content/uploads/wordpress-popular-posts/6908-first_image-220x167.jpg)
![[JavaScript] 超入門:データ型を基礎から理解!文字列・数値・配列・オブジェクトをやさしく解説](https://markleaps.com/blog/wp-content/uploads/2025/06/js-data-types-500x254.jpg)
![[JavaScript] 超入門:letとconstの違いと使い分けをやさしく解説](https://markleaps.com/blog/wp-content/uploads/2025/06/js-let-const-500x254.jpg)
![[JavaScript] 超入門:JavaScriptにおける変数と定数とは?](https://markleaps.com/blog/wp-content/uploads/2025/05/js-variable-constr-500x254.png)
![[JavaScript] 超入門:JavaScript とは?初心者にもわかる『Webページに動きをつける』基本](https://markleaps.com/blog/wp-content/uploads/2025/05/js-what-is-500x254.jpg)