javascript 同じタグの要素全てにイベントを登録する
- 作成日 2021.04.28
- 更新日 2022.08.18
- javascript
- javascript

javascriptで、同じタグの要素全てにイベントを登録するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.81
要素全てにイベントを登録
「getElementsByTagName」で、同じタグのものを全て配列で取得して、for文でイベントを登録することで実現することが可能です。
<button id="btn1" type="button">btn1</button>
<button id="btn2" type="button">btn2</button>
<script>
'use strict';
const arr = document.getElementsByTagName("button");
for (let i = 0; i < arr.length; i++) {
arr[i].onclick = () => { console.log(arr[i]); };
}
</script>
実行結果

以下のように、「スプレッド構文」で配列化して「forEach」で「for文」をアロー関数も使って1行で記述することもできます。
'use strict';
const arr = document.getElementsByTagName("button");
[...arr].forEach( (x, i) => arr[i].onclick = () => { console.log(arr[i]) } );
サンプルコード
以下は、
「実行」ボタンをクリックすると、aタグのリンクを全て無効化する
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
window.onload = () => {
const arr = document.getElementsByTagName("a");
[...arr].forEach( (x, i) => arr[i].onclick = (e) => { e.preventDefault() } );
}
</script>
<body>
<div class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<a id="link1" href="https://mebee.info/" class="bg-green-700 text-white py-4 px-8">リンク</a>
<a id="link2" href="https://mebee.info/" class="bg-blue-700 text-white py-4 px-8">リンク</a>
<a id="link3" href="https://mebee.info/" class="bg-red-700 text-white py-4 px-8">リンク</a>
</div>
</div>
</body>
</html>
全てのaタグのリンクが無効化されていることが確認できます。

-
前の記事
ubuntu21.04にmongokuをインストールする 2021.04.28
-
次の記事
AlmaLinux CPUの情報を確認する 2021.04.28
コメントを書く