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

余生长醉 提交于 2021-01-27 06:08:02

问题


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.


回答1:


Try using this:

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

convertToArray() {
    const shapesHC = document.getElementsByClassName('shape');
    const shapesArrHCSpread = [...(shapesHC as any)];
    console.log(shapesArrHCSpread);
}


来源:https://stackoverflow.com/questions/48153968/how-do-i-convert-a-htmlcollection-into-an-array-without-emptying-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!