Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS ForEach Loops in IE11

Tags:

I am having issues getting a JS loop to work over 4 elements on a page in IE11. I want the function hideImg to run on mouseover on the element that you hovered over.

Here is my code:

elements.forEach( function(element) {     element.addEventListener('mouseover', hideImg); }); 

I think I've found that forEach loops are not supported in IE, how can I easily convert this to a for loop in plain JS?

Kind regards,
Steve

like image 828
Steve Walker Avatar asked Nov 28 '17 14:11

Steve Walker


People also ask

Does foreach work on Internet Explorer 11?

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).

How do I use for each loop in Internet Explorer?

Internet Explorer doesn't support "for each" loops (along with other modern browsers, which have dropped support for them). You will need to change the code to use regular for loops:

What is the difference between foreach() and queryselectorall()?

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 Arrayobjects. (It works with NodeList with ES6, not supported by IE11).

How to solve “object doesn’t support method ‘foreach’ in IE 11?

Open up IE 11 and you will find “Object doesn’t support property or method ‘forEach’” in the console. There are a few simple ways we can solve this, the first is to wrap the DOM selection in a Array.prototype.slice.call to allow IE to iterate through it,


2 Answers

You can do it like this:

var elements = document.getElementsByClassName("test");  for (var i = 0; i < elements.length; i++) {    elements[i].addEventListener('mouseover', hideImg);  }    function hideImg() {    console.log("hideImg called")  }
.test {    width: 40px;    height: 20px;    border: green solid 1px;  }
<div class="test"></div>  <div class="test"></div>  <div class="test"></div>  <div class="test"></div>
like image 153
Nemani Avatar answered Sep 28 '22 17:09

Nemani


This code will fix your issue in IE 11.

Array.prototype.slice.call(elements).forEach( function(element) {     element.addEventListener('mouseover', hideImg); }); 
like image 30
Shailendra Dobhal Avatar answered Sep 28 '22 17:09

Shailendra Dobhal