0

I can console log an HTML collection from the DOM but when I try to log it after it's been converted into an array, it somehow becomes empty.

const results = document.getElementsByClassName("hit-container");
const resultsArr = [...results];
console.log(results);
console.log(resultsArr);

The first console log will return all the elements within the HTML collection. The second console log will return an empty array.

I want to return the array with all the elements so I can perform array functions on the collection of elements.

Using Array.from() will also yield the same issue.

Harrison Greeves
  • 317
  • 3
  • 10
  • `getElementsByClassName()` returns a _live_ collection that updates as elements matching the query are added to the document. `console.log()` is also (in)famous for showing live updates of objects and arrays. **When** you convert the live collection to an array, there were no matching elements – Phil May 04 '22 at 05:02
  • @Phil This is useful to know and I now understand why my code isn't working. But this page - https://stackoverflow.com/questions/32486199/whats-the-difference-between-live-and-not-live-collection-in-javascript-selecto doesn't provide an answer for my specific problem. I still don't know how to convert an HTML collection (live collection) to an array. Even after trying the proposed solutions here - https://stackoverflow.com/questions/222841/most-efficient-way-to-convert-an-htmlcollection-to-an-array – Harrison Greeves May 04 '22 at 05:27
  • You need to convert it to an array **after** the elements are added to your document. I'll add [another link](https://stackoverflow.com/q/14028959/283366) at the top of your question that should help – Phil May 04 '22 at 05:31
  • Okay. Understood. This is what I've come up with based on the link you gave me - ``` document.addEventListener("DOMContentLoaded", () => { const resultsArr = [...results]; console.log(resultsArr); });```. However, nothing appears in the console. Not even null. I don't understand this. I also tried adding ```type="module" to the script tag but the previous issue still arises. – Harrison Greeves May 04 '22 at 06:09

0 Answers0