0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

アコーディオンメニューの.next()、.siblings()、.nextAll()メソッドについて

Last updated at Posted at 2025-02-13
<div class="js-accordion">クリックで開閉</div>
<div class="content">ここが開閉される</div>
<div class="other">これは影響しない</div>
jQuery(".js-accordion").on("click", function () {
  jQuery(this).next().slideToggle();
});

.js-accordionをクリックすると、その直後の.contentが開閉される。

.slideToggle

jQuery(selector).slideToggle(speed, easing, callback);
  • speed(省略可): アニメーションの速さ("slow", "fast" もしくはミリ秒)
  • easing(省略可): 動きの変化(一般的には "swing" や "linear")
  • callback(省略可): アニメーション完了後に実行する関数

.slideToggle()は、対象の要素のdisplayプロパティをnoneblockに切り替える。

※要素のdisplayblock以外(例:inline-block,flexなど)の場合、アニメーション後に display: block;になってしまう点に注意が必要。
この場合は、.slideToggle()の後にcss("display", "flex")などを指定すると元のレイアウトを維持できる。

.next()

.next()はデフォルトで直後の兄弟要素を取得する。

※引数にセレクターを入れることで、直後の兄弟要素の中で条件に合うものだけ取得することができる。

.siblings()

jQuery(".js-accordion").on("click", function () {
  jQuery(this).siblings(".other").slideToggle();
});

.otherを開きたい場合は、.siblings()を使う。

.siblings()ですべての兄弟要素を取得できる。.siblings(".other")というふうにセレクタを.otherと指定することで、兄弟要素の中の.otherのみを取得。

.nextAll()

.nextAll()も後続の兄弟要素をすべて取得できるため、.nextAll(".other")と指定すれば、.otherを開閉できる。

※補足
.siblings()との違いは、.siblings()は前後含めたすべての兄弟要素を取得できるが、.nextAll()は、後続のすべての兄弟要素を取得する。(前は含まない)


ちなみに、これでも.otherを開閉することができる。

jQuery(".js-accordion").on("click", function () {
  jQuery(this).next().next().slideToggle();
});
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?