Irohabook
0
2037

JavaScriptのchildNodesにforEachを適用するときはArray.fromを使う

childNodes は配列でなく、そのままでは forEach を適用できない。下のように Array.from に入れると forEach が使える。

次のコードでは main の子要素をすべて削除している。

const main = document.getElementById('main');
Array.from(main.childNodes).forEach(function (a) {
    a.remove();
})

Array.from は ES2015 から使える。

次の記事

配列