javascript イベント発生元のclassを取得する
- 作成日 2021.08.19
- 更新日 2022.09.27
- javascript
- javascript

javascriptで、イベント発生元のclassを取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 105.0.5195.127
イベント発生元のclassを取得する
イベント発生元のclassを取得するには、「Event.target.className」を使用します。
<input id="btn" class="foo" type="button" value="ボタン" />
<script>
'use strict';
function hoge(e){
console.log(e.target.className)
}
document.getElementById("btn").addEventListener('click', hoge, false)
</script>
実行結果を確認すると、ボタンをクリックすると、クリックされたボタンの要素のclassが取得されていることが確認できます。

また、以下のコードを、
function hoge(e){
console.log(e.target.className)
}
document.getElementById("btn").addEventListener('click', hoge, false)
アロー関数とdocument.getElementByIdを省略して、簡潔に記述することもできます。
const hoge = (e) =>{
console.log(e.target.className)
}
btn.addEventListener('click', hoge, false)
要素内の要素
親要素にイベントを指定すると、子要素で発生したイベントにも影響する場合は、子要素は子要素だけが取得され、親要素も親要素のみが取得されます。
<div id="main" class="oya" style="padding: 10px; margin-bottom: 10px; border: 1px dashed #333333;">
<input id="btn" class="ko" type="button" value="ボタン" />
</div>
<script>
'use strict';
function hoge(e){
console.log(e.target.className)
}
document.getElementById("main").addEventListener('click', hoge, false)
</script>
実行結果

サンプルコード
以下は、
「実行」ボタンをクリックした際に、クリック元の要素のclassを表示するサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
window.onload = () => {
btn.onclick = (e) => { bar.innerHTML = e.target.className }
}
</script>
<body>
<div class="container mx-auto my-56 w-1/3 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 class="font-semibold text-black-500 text-lg mr-auto">実行結果</h1>
<h1 id="bar" class="font-semibold text-gray-500 text-lg mr-auto"></h1>
<input id="btn" type="button" value="実行"
class="mb-2 md:mb-0 bg-transparent hover:bg-orange-300 text-orange-700 font-semibold hover:text-white py-2 px-4 border border-orange-300 hover:border-transparent rounded" />
</div>
</div>
</body>
</html>
実行結果を確認すると、クリックした要素のclassが表示されていることが確認できます。

-
前の記事
Ruby 配列の先頭からを条件を満たすものを取得する 2021.08.18
-
次の記事
C# numericUpDownの位置を移動させる 2021.08.19
コメントを書く