JavaScript querySelectorAllで複数のid要素を取得するサンプル
環境
Windows 10 home 64bit
Google Chrome 107.0.5304.122(Official Build) (64 ビット)
構文
const 変数名 document.querySelectorAll('#セレクタid1, #セレクタid2’);
querySelectorAllメソッドを使って複数のidの要素を取得します。
使用例
<!DOCTYPE html>
<html>
<body>
<div id="cityA">tokyo</div>
<div id="cityB">oosaka</div>
<button onclick="myFunction()">表示</button>
<script>
function myFunction() {
const cftLst= document.querySelectorAll('#cityA, #cityB');
for(let item of cftLst){
console.log( item.textContent )
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<div id="cityA">tokyo</div>
<div id="cityB">oosaka</div>
<button onclick="myFunction()">表示</button>
<script>
function myFunction() {
const cftLst= document.querySelectorAll('#cityA, #cityB');
for(let item of cftLst){
console.log( item.textContent )
}
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <div id="cityA">tokyo</div> <div id="cityB">oosaka</div> <button onclick="myFunction()">表示</button> <script> function myFunction() { const cftLst= document.querySelectorAll('#cityA, #cityB'); for(let item of cftLst){ console.log( item.textContent ) } } </script> </body> </html>
実行結果
「表示」ボタンを押すと、コンソールに下記メッセージを出力します
tokyo
oosaka