javascript 複数のidを指定して取得する
- 作成日 2022.12.29
- javascript
- javascript

javascriptで、複数のidを指定して取得するサンプルコードを記述してます。「querySelectorAll」に「id」を複数指定することで可能です。存在しない「id」を指定してもエラーにはなりません。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 108.0.5359.125
複数のidを指定して取得
複数の「id」を指定して取得するには、「querySelectorAll」を使用します。
<div id="one">aaa</div>
<div id="two">bbb</div>
<div id="three">ccc</div>
<script>
const nodelist = document.querySelectorAll('#one, #two, #three');
for(let item of nodelist){
console.log( item.textContent )
}
</script>
実行結果

「NodeList」は配列として処理できるので「forEach」なども使用できます。
const nodelist = document.querySelectorAll('#one, #two, #three');
nodelist.forEach(v => {
console.log(v.textContent);
});
配列で「id」を用意してから取得することもできます。
const ids = ['one', 'two', 'three'];
const nodelist = document.querySelectorAll(
ids.map(id => `#${id}`).join(', ')
);
for(let item of nodelist){
console.log( item.textContent )
}
存在しないidを指定
存在しない「id」を指定してもエラーにはなりません。
const nodelist = document.querySelectorAll('#four, #five');
nodelist.forEach(v => {
console.log(v.textContent); // エラーにならず何も出力されない
});
サンプルコード
以下は、
「実行」ボタンをクリックすると、複数の「id」を一括で指定して値を変更する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- MDB -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>
<body>
<div class="container text-center w-75 mx-auto" style="margin-top:200px">
<h2><span class="badge badge-warning"></span></h2>
<h2><span class="badge badge-warning">結果</span></h2>
<button type="button" onclick="hoge()" class="btn btn-raised btn-warning">
取得
</button>
</div>
<script>
let obj = { one: null, two: null, three: 3 };
// 表示用要素取得
let elm = document.getElementsByClassName("badge")[0];
// JSON 文字列に変換して表示
elm.textContent = JSON.stringify(obj);
const hoge = () => {
// 表示用要素取得
let elm = document.getElementsByClassName("badge")[1];
for (const key in obj) {
if (obj[key] === null) delete obj[key];
}
// JSON 文字列に変換して表示
elm.textContent = JSON.stringify(obj);
}
</script>
</body>
</html>
取得されていることが確認できます。

-
前の記事
Flutter 角が欠けたElevatedButtonを作成する 2022.12.28
-
次の記事
Google ドライブ ドライブ内に移動するショートカットキー 2022.12.29
コメントを書く