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?

More than 3 years have passed since last update.

jQuery セレクタに複数の要素を指定する方法

Posted at

jQuery セレクタに複数の要素を指定したい時

例えば、clickイベント内の処理を複数の要素(今回はdata属性)で使用したい時、以下のように書くだろう。

index.js
  $("[data-aaa], [data-bbb], [data-ccc], ...).click(function () {
   ...
  });

このままだと、指定したい要素がもっと増えた時は、横に長くなり可読性が落ちる。
そこで、セレクタに変数を代入し複数の要素を縦書き、可読性をよくする方法を共有します。

##方法

index.js

  // 指定したい要素を配列に定義しておく
  let targetAttrArr = [
    '[data-aaa]',
    '[data-bbb]',
    '[data-ccc]',
     ...
  ];

  // 配列内の文字列を結合してtargetに代入
  let target = '';
  targetAttrArr.forEach(function (element, index) {
    target += element;
    if ( index != (targetAttrArr.length - 1)) {
      target += ', ';
    }
  });

  // target変数をセレクタで代入
  $(target).click(function () {
    ...
  });

OK

0
0
1

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?