Javascript 从HTMLCollection输出所有项
我有一个从字符串转换而来的Javascript 从HTMLCollection输出所有项,javascript,html,Javascript,Html,我有一个从字符串转换而来的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
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转换为数组?artistsPlaceholder.innerHTML=allArtistTiles
无法工作,因为innerHTML
setter需要一个字符串。您需要附加这些项。在现代浏览器中,您可以使用
artistsPlaceholder.append(...allArtistTiles);
这需要对和的支持
或者,你可以写
Array.from(allArtistTiles).forEach((elem) => artistsPlaceholder.appendChild(elem));
它使用(可由数组.prototype.slice.call替换)和(可由常规函数替换)
如果要对
循环使用,仍然建议在数组上循环(例如从array.prototype.slice.call(allArtistTiles)
)以避免
严格来说,没有必要将HTMLCollection
转换为数组
,但是数组
更容易使用。artistsPlaceholder.innerHTML=allArtistTiles
无法工作,因为innerHTML
setter需要一个字符串。您需要附加这些项。在现代浏览器中,您可以使用
artistsPlaceholder.append(...allArtistTiles);
这需要对和的支持
或者,你可以写
Array.from(allArtistTiles).forEach((elem) => artistsPlaceholder.appendChild(elem));
它使用(可由数组.prototype.slice.call替换)和(可由常规函数替换)
如果要对
循环使用,仍然建议在数组上循环(例如从array.prototype.slice.call(allArtistTiles)
)以避免
严格来说,没有必要将HTMLCollection
转换为数组
,但是数组
更容易使用。innerHTML
需要的是字符串,而不是对象。使用artistsPlaceholder.append(…allArtistTiles)代码>如果可以使用and。innerHTML
需要字符串,而不是对象。使用artistsPlaceholder.append(…allArtistTiles)代码>如果可以使用和。