Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - .forEach() not working in IE8

I have created this little interaction for one of the platforms at work - http://jsfiddle.net/S79qp/426/

It works fine in all browsers apart form IE8. When I run the console it seems to be this section that it is having problems with...

Array.prototype.forEach.call(l, function(item) {
        a.push(jQuery(item).text());
   });

Can someone show me an IE8 friendly alternative so I can make it compatible for the versions required?

like image 411
Milo-J Avatar asked Apr 24 '13 08:04

Milo-J


2 Answers

If all you want is forEach() in IE8:

if (typeof Array.prototype.forEach != 'function') {
    Array.prototype.forEach = function(callback){
      for (var i = 0; i < this.length; i++){
        callback.apply(this, [this[i], i, this]);
      }
    };
}

This will behave as expected in any browser that doesn't have it built-in.

like image 150
Chad Hedgcock Avatar answered Oct 15 '22 00:10

Chad Hedgcock


Use the jQuery.each method:

jQuery.each(l, function(index, item){
  a.push(jQuery(item).text());
});

If the target array is empty from start, you can use the jQuery.map method for this instead:

var a = jQuery.map(l, function(item){
  return jQuery(item).text();
});
like image 37
Guffa Avatar answered Oct 15 '22 00:10

Guffa