LoginSignup
99
89

More than 5 years have passed since last update.

IEで NodeList を forEach するとエラーになる問題の対処方

Posted at

原因はIEがサポートしていないから。

jQuery のセレクターはやめて、document.querySelectorAll でDOM要素を取得し、取得した数だけループして何か処理をしたい際、IEでは動かなかった(サポートされていなかったのを知らなかった...)ので、その解決方法のメモ。

やりたいこと

何かの要素が複数個あり、それらを取得。
取得した数だけ、別の処理を行いたい。

html
<ul>
  <li class="js-get_listItems">item0</li>
  <li class="js-get_listItems">item1</li>
  <li class="js-get_listItems">item2</li>
</ul>

Chromeでは動くのであまり気にしていなかった書き方

querySelectorAll で取得した NodeList に対して NodeList.forEach() でループ処理する方法。これはIEでは動作しないです。

javascript
var nodelist = document.querySelectorAll('.js-get_listItems');

nodelist.forEach(function(elem, index){
  elem.textContent = "アイテム" + index;
});

//item0 → アイテム0 に書き換えしている
//item1 → アイテム1 に書き換えしている
//item2 → アイテム2 に書き換えしている

MDN:NodeList.forEach()
https://developer.mozilla.org/ja/docs/Web/API/NodeList/forEach

記事の下あたりにInternet ExplorerはNo supportと記述があります。

for...of ではEdgeならOK。それ以前(IE11ではダメ)

MDNにある方法。
for...of ループであれば、NodeList オブジェクトを正しく扱うことができます。
https://developer.mozilla.org/ja/docs/Web/API/NodeList

MDNに記載されている方法
var list = document.querySelectorAll( 'input[type=checkbox]' );
for (var item of list) {
  item.checked = true;
}

と記述があるが、IE Edge から利用可能。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/for...of

つまり、IE11では動作してくれない。。

回避策

javascript
var nodelist = document.querySelectorAll('.js-get_listItems');

var node = Array.prototype.slice.call(nodelist,0); 
node.forEach(function(elem, index){
  elem.textContent = "アイテム" + index;
});

NodeListで取得したものをArray.prototype.slice.callで配列として取り出し、Array.prototype.forEach()でループ処理する方法。

stackoverflowに投稿がありました、なるほど。
http://stackoverflow.com/questions/13433799/why-doesnt-nodelist-have-foreach

99
89
0

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
99
89