Steve Walker
Steve Walker

Reputation: 281

JS ForEach Loops in IE11

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

Upvotes: 23

Views: 40688

Answers (4)

Mike Godin
Mike Godin

Reputation: 3937

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.

Upvotes: 4

Vince
Vince

Reputation: 869

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;
  }

Upvotes: 11

Nemani
Nemani

Reputation: 784

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>

Upvotes: 25

Shailendra Dobhal
Shailendra Dobhal

Reputation: 191

This code will fix your issue in IE 11.

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

Upvotes: 19

Related Questions