How to convert HTMLcollection returned when using getElementsByClassName into Array

39 Views Asked by At

Array.from() or Array.prototype.slice.call() or using for loop to add htmlcollection into array not working on converting HTMLcollection from getElementsByClassName into array so that i can iterate through the data. NOTE: dont want to use querySelectorAll cause contents are added dynamically and so querySelectorAll not fetching the elements. Consider codes:below

document.addEventListener('DOMContentLoaded', function () {

    const convochats = document.getElementsByClassName('onechat');
    console.log(convochats); //This return a HTMLcollection of elements with onechat class

    // case 01:
    let convochatsArray_case01 = [];
    for (let i = 0; i < convochats.length; i++) {
        convochatsArray.push(convochats[i])
        console.log(convochatsArray_case01); //This return empty array
    }

    // case 02
    let convochatsArray_case02 = Array.from(convochats);
    console.log(convochatsArray_case02); //This return empty array

    // case 03
    let convochatsArray_case03 = Array.prototype.slice.call(convochats);
    console.log(convochatsArray_case03); //This return empty array
})

I was trying to convert HTMLcollection into array so that i can iterate through them

1

There are 1 best solutions below

0
Quentin On

You can’t usefully convert the return value of getElementsByClassName to an array for the same reason you can’t use querySelectorAll.

The elements don’t exist at the time you try to create the array. The array also isn’t live.

You need to create your array at a time when the elements exist.