LoginSignup
7
6

More than 5 years have passed since last update.

querySelectorAll()の戻り値はArrayじゃないよ

Posted at
var divList = document.querySelectorAll('div');
var a = divList[0];// 1つ目の要素
var b = divList[1];// 2つ目の要素

divListは一見Arrayのように見えるが…

console.log(divList instanceof Array);// false
divList.forEach(function(v, i) { console.log(i); });// エラー

Arrayじゃない。
forEachとかmapとか使えない。
気をつけろ。

じゃあquerySelectorAll()の戻り値は何なんだ

答えはNodeList。
これで確認できる。

console.log(toString.call(divList));

forEachとか使いたい時はどうする?

Arrayからメソッド取ってくる
参考:mozillaのNodeListのworkaround

function mixinArray(target) {
  var arrayMethods = Object.getOwnPropertyNames(Array.prototype);
  arrayMethods.forEach(attachArrayMethodsToNodeList);
  function attachArrayMethodsToNodeList(methodName) {
    if(methodName !== "length") {
      target[methodName] = Array.prototype[methodName];
    }
  };
}

mixinArray(NodeList.prototype);

NodeListレベルで変更するのは影響範囲が広くてヤダ!
ってときはインスタンスに対して適用すればイイ。

mixinArray(divList);
7
6
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6