本記事では、要素の表示・非表示をCSSを使わずにjQueryのみで簡単に実装する方法について解説しています。
JavaScriptの学習におすすめ書籍
1冊ですべて身につくJavaScript入門講座

メリット
- 誰でも分かるように嚙み砕いて説明してくれる
- アニメーションの知識が深く学べる
- 1つのWebサイトを作りながら学べる


Amazon Kindle Unlimitedに登録すると、月額980円で読み放題だからオススメだよ!



初回30日間は無料だから、まだ登録したことのない人はぜひ試してみてね!
全プログラマー必見!
変数名/関数名にもう悩まない!
変数名/関数名にもう悩まない!
リーダブルコード


メリット
- 美しいコードが書けるが自然と書けるようになる
- 他の開発者が理解しやすいコードになる
著:Dustin Boswell, 著:Trevor Foucher, 解説:須藤 功平, 翻訳:角 征典
¥2,640 (2023/07/23 02:48時点 | Amazon調べ)


目次
要素を非表示するhide()
要素を非表示にするには、hide()メソッドを使用します。使い方は以下のとおりです。
$("セレクタ").hide();



ボタンをクリックしたら要素が非表示になるサンプルコードを用意したので、動作確認してみましょう!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<p id="point">ボタンをクリックすると非表示になるよ!</p>
<button id="btn">ボタン</button>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="index.js"></script>
</body>
</html>
$("#btn").on("click", function () {
$("#point").hide();
});
要素を表示するshow()
要素を表示にするには、show()メソッドを使用します。使い方は以下のとおりです。
$("セレクタ").show();



ボタンをクリックしたら要素が表示されるサンプルコードを用意したので、動作確認してみましょう!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<p id="point" style="display:none;">要素が表示されたよ!</p>
<button id="btn">ボタン</button>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="index.js"></script>
</body>
</html>
$("#btn").on("click", function () {
$("#point").show();
});
要素の表示・非表示を繰り返すhide()
ユーザーがアクションを起こした際に要素の表示・非表示を繰り返す処理を実装をする場合、先ほど紹介したhide()メソッドとshow()メソッドを使って実装することは可能です。しかし、特定のクラスやdata属性の値などを付与して、出し分ける必要があり少し手間がかかります。
そこで、今回はそんな手間を全て省略して簡潔に実装できるtoggle()メソッドを紹介します。使い方は以下のとおりです。
$("セレクタ").toggle();



ボタンをクリックすると表示・非表示を繰り返すサンプルコードを用意したので、動作確認してみましょう!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<p id="point">ボタンをクリックすると表示・非表示を繰り返すよ!</p>
<button id="btn">ボタン</button>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="index.js"></script>
</body>
</html>
$("#btn").on("click", function () {
$("#point").toggle();
});