javascript 取得した要素を条件を指定して抽出する
- 作成日 2021.04.15
- 更新日 2022.08.16
- javascript
- javascript

javascriptで、取得した要素を条件を指定して抽出するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.81
条件を指定して抽出
「getElementsByTagName」で、同じタグの要素を全て「スプレッド構文」で配列で取得し「filter」で条件を指定して抽出します。
<button id="btn1" class="hoge" type="button">btn1</button>
<button id="btn2" class="foo" type="button">btn2</button>
<button id="btn3" class="hoge" type="button">btn3</button>
<script>
'use strict';
// buttonタグの要素を全て取得
const arr = document.getElementsByTagName("button");
// classがhogeのもののみ抽出
const result = [...arr].filter( x => x.classList.contains('hoge') );
// 結果を表示
console.log(result);
</script>
実行結果

その他の方法は、以下をご参照下さい。
サンプルコード
以下は、
「実行」ボタンをクリックすると、まずチャックされているチェックボックス数を表示する
サンプルコードとなります。
※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>
const check = (name, ...values) => {
const elm = document.getElementsByName(name);
elm.forEach(x => x.checked = values.includes(x.value));
}
const hoge = () => {
const arr = document.getElementsByTagName("input");
const checked = [...arr].filter(x => x.checked);
result.innerHTML = checked.length;
}
window.onload = () => {
btn.onclick = () => { check('hoge', 'checkbox-1', 'checkbox-3'); hoge(); };
}
</script>
<body>
<div class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<p id="result" class="bg-pink-700 text-white py-2 px-8 rounded-full mb-3 mt-4">チェックされている数</p>
</div>
<div class="flex justify-center">
<div class="mt-2">
<div>
<label class="inline-flex items-center">
<input type="checkbox" name="hoge" value="checkbox-1">
<span class="ml-2">checkbox-1</span>
</label>
</div>
<div>
<label class="inline-flex items-center">
<input type="checkbox" name="hoge" value="checkbox-2">
<span class="ml-2">checkbox-2</span>
</label>
</div>
<div>
<label class="inline-flex items-center">
<input type="checkbox" name="hoge" value="checkbox-3">
<span class="ml-2">checkbox-3</span>
</label>
</div>
</div>
</div>
<div class="flex justify-center">
<button id="btn" type="button"
class="mt-5 bg-transparent border border-yellow-500 hover:border-yellow-300 text-yellow-500 hover:text-yellow-300 font-bold py-2 px-4 rounded-full">
実行
</button>
</div>
</div>
</body>
</html>
チェックされた要素の数がカウントされていることが確認できます。

-
前の記事
AlmaLinux 最新のnode.jsをインストールするまでの手順 2021.04.15
-
次の記事
python Pillowを使って画像を表示する 2021.04.15
コメントを書く