I have added the forEach polyfill to the top of my JavaScript file however Internet Explorer is still saying that it doesn't support the function.
I basically want to loop over the results of a querySelector however I do use forEach on some other array objects in my script.
This all works fine on Chrome.
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback/*, thisArg*/) {
var T, k;
if (this === null) {
throw new TypeError('this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = arguments[1];
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
(function() {
var instance = null,
container;
// Constructor
this.MarvLightbox = function() {
// Initialise plugin
this.init();
};
// Initilise the plugin
MarvLightbox.prototype.init = function() {
document.querySelectorAll('[data-click]').forEach(function(e) {
e.addEventListener('click', [clickevent]);
});
};
}());
Shouldn't adding the polyfill fix this issue with IE?
One of the main one is using forEach on DOM elements. In modern browsers it's pretty easy to select DOM elements and loop through them to add something like an eventListener . Open up IE 11 and you will find “Object doesn't support property or method 'forEach'” in the console.
IE11 – The object does not support the “forEach” property or method.
Another way to make IE9+ support forEach
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<span class="demo">See me.</span>
<span class="demo">See me.</span>
<span class="demo">See me.</span>
<span class="demo">See me.</span>
<script>
// Function to make IE9+ support forEach:
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
// Works with Nodelists (i.e. HTMLcollections):
var demos = document.querySelectorAll('.demo');
demos.forEach(function(item) {
item.style.color = 'red';
});
// As well as with Arrays:
var gherkins = ['gher1', 'gher2', 'gher3'];
gherkins.forEach(function(item) {
console.log(item);
});
</script>
</body>
</html>
Tested in IE11, and according to its emulate function, also works in 10 and 9 (not 8).
You are adding a prototype to the Array
object and try to use it on a NodeList
(which is what querySelectorAll returns instead of an array), that won't work. Make an Array out of the node List, or use
Array.prototype.forEach.call(document.querySelectorAll('[data-click]'), function (e) {
// your code
});
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