1

I have an HTMLCollection that I have converted from a string:

let el = document.createElement('html');

el.innerHTML = data; // This data is my HTML string

let allArtistTiles = el.getElementsByClassName('artistTile');

console.log(allArtistTiles); // I used this to check I see the HTML Collection

let artistsPlaceholder = document.getElementById('artistsPlaceholder')

artistsPlaceholder.innerHTML = allArtistTiles

It’s the last line I’m not sure about. How do I actually show all the elements in the HTMLCollection? Do I have to iterate through the HTMLCollection? Also, is it necessary to convert the HTMLCollection into an array?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
userMod2
  • 8,312
  • 13
  • 63
  • 115
  • 4
    `innerHTML` expects a string, not an object. Use `artistsPlaceholder.append(...allArtistTiles);` if you can use [spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [`append`](https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append). – Sebastian Simon Aug 17 '19 at 07:36

1 Answers1

0

artistsPlaceholder.innerHTML = allArtistTiles; wouldn’t work because the innerHTML setter expects a string. You need to append the items. In modern browsers you can use

artistsPlaceholder.append(...allArtistTiles);

which needs support for both spread and append.


Alternatively, you can write

Array.from(allArtistTiles).forEach((elem) => artistsPlaceholder.appendChild(elem));

which uses Array.from (which can be replaced by Array.prototype.slice.call), forEach and arrow functions (which can be replaced by regular functions).


If you’re going to use for loops, it’s still advisable to loop over the array (e.g. from Array.prototype.slice.call(allArtistTiles)) to avoid unexpected HTMLCollection behavior.

It’s not strictly necessary to convert the HTMLCollection to an Array, but an Array is easier to work with.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75