jQuery toggleClassでclassの追加・削除を交互に実行するサンプル

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1

書式
$(セレクタ名).toggleClass(className);
selectorがclassNameに指定したclassを持っていれば削除し、なければ追加します。
toggleClass()はclassの追加・削除を交互に実行します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<style>
.cft {
color: red;
}
</style>
<script>
$(document).ready(function(){
$('.kk').on('click', function () {
$('.kk').toggleClass('cft');
});
});
</script>
</head>
<body>
<button class="kk">テスト</button>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <style> .cft { color: red; } </style> <script> $(document).ready(function(){ $('.kk').on('click', function () { $('.kk').toggleClass('cft'); }); }); </script> </head> <body> <button class="kk">テスト</button> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

<style>
.cft {
  color: red;
}
</style>
<script>
$(document).ready(function(){
$('.kk').on('click', function () {
    $('.kk').toggleClass('cft');
});
});
</script>
</head>
<body>

<button class="kk">テスト</button>

</body>
</html>

実行結果
「テスト」ボタンをクリックする度に文字の色が赤色と白色に変わります。

jQuery

Posted by arkgame