ねこくん
document.querySelectorAll() で取得した値をmapしようとしたら、できなかったんだけど!Yuki
document.querySelectorAll()はArrayじゃなくてNodeListを返すから、mapは使えないんだよね。ねこくん
NodeListって配列っぽいのに配列じゃないんだね。。。NodeListはmapできない
document.querySelectorAll()はArrayではなく、NodeListを返します。
そして、mapは配列(Array)に対してのメソッドなので、NodeListのままでは使えません。
ということで、Arrayにしてあげればmapできます。
これで解決!
😍 Array.from()でArrayに変換
const hoge = document.querySelectorAll('.js-hoge');
const hogeArray = Array.from(hoge)↓ちなみにforEach()は使用可能です。
NodeListはArrayとは異なりますが、forEach()メソッドで処理を反復適用することは可能です。Array.from()を使うことでArrayに変換することができます。引用元:MDN NodeList
https://developer.mozilla.org/ja/docs/Web/API/NodeList
おまけ
Array.from()はES6からなので、使えない場合はこんな方法もあります。
const hoge = document.querySelectorAll('.js-hoge');
const hogeArray = [].slice.call(hoge);それでは皆さん、ステキなJSライフを!


