Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE supports forEach(...) when invoked fromthe console but not when called from the code

I'm running this snippet the console. In IE it produces the output just as expected. Running the same in Cr and FF for reference confirms the congruence of behavior.

["a", "b"].forEach(function(element) {
  console.log(element);
});

However, when running the following script, I'm getting errors telling me that the object hasn't forEach(...) declared on it. The issue occurs in IE but not in Cr nor FF.

var menus = document.querySelectorAll("ul.application>li>a");
menus.forEach(function(element) { ... }

I've checked that the variable menus is declared and that picking it's elements produces what I would expect, i.e. menus[0] exists and is a tag. It looks a bit differently in IE compared to the others but it might be just the different rendition.

I've been blessed working with Cr and FF so my experience in dealing with IE is limited. Googling didn't give me much wisdom, neither.

How do I troubleshoot it further?

like image 567
Konrad Viltersten Avatar asked Dec 14 '16 12:12

Konrad Viltersten


2 Answers

Basically document.querySelectorAll would return a nodeList an array like object not an array. You have to convert it to an array before invoking array functions over that.

var menus = document.querySelectorAll("ul.application>li>a");
menus = [].slice.call(menus);
menus.forEach(function(element) { ... });

If your environment supports ES6 then you can use Array.from()

var menus = document.querySelectorAll("ul.application>li>a");
menus = Array.from(menus);
menus.forEach(function(element) { ... });
like image 199
Rajaprabhu Aravindasamy Avatar answered Nov 11 '22 18:11

Rajaprabhu Aravindasamy


The best solution would be to add one line at the beginning:

window.NodeList && !NodeList.prototype.forEach && (NodeList.prototype.forEach = Array.prototype.forEach) // make IE support forEach

And after that, you can use forEach in IE like in other normal browsers.

like image 22
Dmitry Shashurov Avatar answered Nov 11 '22 19:11

Dmitry Shashurov