JS ForEach Loops in IE11

Viewed 39416

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

4 Answers

This code will fix your issue in IE 11.

Array.prototype.slice.call(elements).forEach( function(element) {
    element.addEventListener('mouseover', hideImg);
});

Just add this to your code at the top of it the code provided is supported in all Browsers

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
  }

Can also use the somewhat more compact:

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

Or even more compact:

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

Note that some programmers prefer to avoid the latter method because it creates an otherwise unused empty array.

Related