7

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.

zero298
  • 25,467
  • 10
  • 75
  • 100
Paulo_dev
  • 81
  • 1
  • 7
  • 1
    All three of those methods return a non-empty array when I tested it. Perhaps your problem is somewhere else in your code? – Khauri Jan 08 '18 at 16:11
  • Thanks for quick response - this is the entirety of my code. It's just one html file and a js file. – Paulo_dev Jan 08 '18 at 16:16
  • 2
    Where is the JavaScript in your code located, above or below your HTML? If it is above your HTML (in the head), those elements don't exist to be queried until **after** your JavaScript has run. – zero298 Jan 08 '18 at 16:19
  • Read this question and see if it applies: https://stackoverflow.com/a/24070373/691711 – zero298 Jan 08 '18 at 16:22
  • 1
    Yep, my script tag was in the head. Now that I've moved it to the end of the body it works fine. *Facepalm* – Paulo_dev Jan 08 '18 at 16:25

1 Answers1

2

Try using this:

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

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