我有一个从字符串转换而来的HTMLCollection:
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这是我不确定的最后一句话。如何实际显示HTMLCollection中的所有元素?我必须遍历HTMLCollection吗?另外,是否有必要将HTMLCollection转换为数组?
发布于 2019-08-17 16:05:10
artistsPlaceholder.innerHTML = allArtistTiles;无法工作,因为innerHTML设置器需要一个字符串。您需要追加这些项。在现代浏览器中,您可以使用
artistsPlaceholder.append(...allArtistTiles);或者,您可以编写
Array.from(allArtistTiles).forEach((elem) => artistsPlaceholder.appendChild(elem));它使用Array.from (可由Array.prototype.slice.call替代)、forEach和arrow functions (可由常规函数替代)。
如果你打算使用for循环,仍然建议循环遍历数组(例如来自Array.prototype.slice.call(allArtistTiles)),以避免unexpected HTMLCollection behavior。
不一定要将HTMLCollection转换为Array,但Array更易于使用。
https://stackoverflow.com/questions/57534254
复制相似问题