javascript HTMLCollectionを配列として使用してループさせる

javascript HTMLCollectionを配列として使用してループさせる

javascriptで、HTMLCollectionを配列として使用してループさせるサンプルコードを掲載してます。「スプレッド構文」や「Array.from」で配列化することが可能です。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 109.0.5414.75

HTMLCollectionを配列として使用してループさせる

HTMLCollectionを配列として使用してループさせるするには「スプレッド構文」を使用することで可能です。

実際に、クラス名に「bar」が含まれている要素の「textContent」を取得してみます。

<ul class="foo">
    <li class="hoge bar">1</li>
    <li class="hoge">2</li>
    <li class="hoge bar">3</li>
    <li class="hoge">4</li>
    <li class="hoge huga">5</li>
</ul>

<button id="btn">取得</button>

<script>

'use strict';

document.getElementById('btn').addEventListener('click', function () {

    const elm = document.getElementsByClassName('hoge');

    const arr = [...elm].filter(v => v.classList.contains('bar')).map(v => v.textContent);

    console.log(arr)

});

</script>

実行結果を見ると、取得されているが確認できます。

その他の方法

他にも「Array.from」や、

document.getElementById('btn').addEventListener('click', function () {

    const elm = document.getElementsByClassName('hoge');

    const arr = Array.from(elm).filter(v => v.classList.contains('bar')).map(v => v.textContent);

    console.log(arr)

});

「[].slice.call」

document.getElementById('btn').addEventListener('click', function () {

    const elm = document.getElementsByClassName('hoge');

    const arr = [].slice.call(elm).filter(v => v.classList.contains('bar')).map(v => v.textContent);

    console.log(arr)

});

「Object.values」を使用する方法があります。

document.getElementById('btn').addEventListener('click', function () {

    const elm = document.getElementsByClassName('hoge');

    const arr = Object.values(elm).filter(v => v.classList.contains('bar')).map(v => v.textContent);

    console.log(arr)

});