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
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).
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:
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).
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,
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>
This code will fix your issue in IE 11.
Array.prototype.slice.call(elements).forEach( function(element) { element.addEventListener('mouseover', hideImg); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With