Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a HTMLCollection into an array, without emptying it?

I am trying to convert an HTMLCollection of 4 divs into an array, but every method I try seems to result in the array being emptied.

<div class="container">
        <div class="shape" id="one"></div>
        <div class="shape" id="two"></div>
        <div class="shape" id="three"></div>
        <div class="shape" id="four"></div>
</div>

Methods I've attempted - as per this previous question:

var shapesHC = document.getElementsByClassName('shape');
//gives HTMLCollection

var shapesArrCall = [].slice.call(shapesHC);
// returns empty array

var shapesArrHC = Array.from(shapesHC);
// returns empty array

var shapesArrHCSpread = [...shapesHC];
// returns empty array

I'd really appreciate if anyone can point out where I'm going wrong here.

Thanks.

like image 767
Paulo_dev Avatar asked Nov 07 '22 12:11

Paulo_dev


1 Answers

Try using this:

setTimeout(() => {
    this.convertToArray();
});

convertToArray() {
    const shapesHC = document.getElementsByClassName('shape');
    const shapesArrHCSpread = [...(shapesHC as any)];
    console.log(shapesArrHCSpread);
}
like image 155
Carlos Tenorio Pérez Avatar answered Nov 14 '22 23:11

Carlos Tenorio Pérez