admin管理员组

文章数量:1332388

forEach loops are supposed to be working in IE11 and diplay

Object doesn't support property or method 'forEach'.

It should be working since it's an ECMAScript-5 function and IE11 supports it.

However, my code here is not working:

var alltable = document.querySelectorAll('*[id^="table_"]'); //Select all elements with the id starting by "table_"
    alltable.forEach(function(element) {
                // Do some code
                });

Any idea why ?

forEach loops are supposed to be working in IE11 and diplay

Object doesn't support property or method 'forEach'.

It should be working since it's an ECMAScript-5 function and IE11 supports it.

However, my code here is not working:

var alltable = document.querySelectorAll('*[id^="table_"]'); //Select all elements with the id starting by "table_"
    alltable.forEach(function(element) {
                // Do some code
                });

Any idea why ?

Share Improve this question asked Apr 18, 2019 at 8:12 GawetGawet 3154 silver badges15 bronze badges 3
  • the title is a bit misleading ... – Nina Scholz Commented Apr 18, 2019 at 8:17
  • 1 Possible duplicate of Why is forEach method breaking in IE? – delinear Commented Apr 18, 2019 at 8:19
  • 1 Well, how would you call it ? That was my problem and I just wanted to help other who encounter the same... – Gawet Commented Apr 18, 2019 at 8:19
Add a ment  | 

1 Answer 1

Reset to default 7

Well myself,

forEach() is actually working on IE11, just be careful on how you call it.

querySelectorAll() is a method which return a NodeList. And on Internet Explorer, foreach() only works on Array objects. (It works with NodeList with ES6, not supported by IE11).

To fix this, some would advice a polyfill, which could work great, but you can also simply convert your NodeList into an array with the slice.call() method: (Explained here)

var alltable = document.querySelectorAll('*[id^="table_"]'); //Select all elements with the id starting by "table_"
var alltableArray= Array.prototype.slice.call(alltable);
    alltableArray.forEach(function(element) {
                // Do some code
                });

Or:

var alltable = Array.prototype.slice.call(document.querySelectorAll('*[id^="table_"]')); //Select all elements with the id starting by "table_"
    alltable.forEach(function(element) {
                // Do some code
                });

To sum up: Be sure you're using it on an Array object and not a NodeList.

Hope that can help someone.

本文标签: internet explorerJavascriptforEach() loops not working on IE11Stack Overflow