LoginSignup
16
18

More than 3 years have passed since last update.

【2019年版】 JavaScriptで何番目の要素か取得する方法

Last updated at Posted at 2019-10-16

要素の中で何番目の要素がクリックされたかをJavaScriptで取得しようとした時、従来は

Array.prototype.indexOf.call("集合の要素", "目的の要素")

などで取得していましたが、ES2015で追加されたfindeIndex()メソッドを使えば何番目の要素か取得できます。

elements.findIndex(element => {
  return element === target // target:一意に識別するもの。例えばevent.targetなど
})

具体例

以下はリストをクリックした時に何番目の要素をクリックしたかを取得するスクリプトです。

<ul>
  <li>
  </li>
  <li>
  </li>
  <li>
  </li>
  <li>
  </li>
  <li>
  </li>
</ul>
const lists = Array.from(document.querySelectorAll("li"));
lists.forEach(li => {
  li.addEventListener("click", e => {
    const index = lists.findIndex(list => list === e.target);
    console.log(index);
  });
});

findeIndex()は配列にしか適用できないので、const lists = Array.from(document.querySelectorAll("li"));で配列様オブジェクトを配列に変換しています。liaddEventListenerでクリックイベントを付与し、クリックした要素とli要素の配列(lists)の要素が合致したものをfindIndex()を使ってインデックス番号を返しています。

See the Pen 何番目? by Nishihara (@Nishihara) on CodePen.

応用

上記の使い方ですと、indexOf()と大差ありません。findIndex()は中でテスト関数を満たせば配列のインデックスを返してくれるので、特定のクラスを持った要素が何番目か、といった使い方もできます。

<ul>
  <li>
  </li>
  <li>
  </li>
  <li class="active">
  </li>
  <li>
  </li>
  <li>
  </li>
</ul>

<button>何番目の要素がアクティブか取得</button>
const button = document.querySelector("button");
const lists = Array.from(document.querySelectorAll("li"));

button.addEventListener("click", () => {
  const index = lists.findIndex(list =>
    Array.from(list.classList).includes("active")
  );
  console.log(index);
});

findIndex()を使えば、activeのクラス名を持った要素が何番目かを容易に知ることができます。indexOfと違ってマッチさせる必要はなく、trueを返せば良いので、柔軟な使い方が可能です。

See the Pen 何番目?(activeクラスを持っている要素) by Nishihara (@Nishihara) on CodePen.

互換性

findeIndex()はES2015からなのでIE11では動きませんが、互換コードはあるので対応も可能です。→ Array.prototype.findIndex() - JavaScript | MDN

16
18
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
16
18