Object doesn’t support property or method ‘indexOf’ in IE 8 – Fix

This error usually comes, if you tested your code in all modern browsers but missed in earlier version of IE. As Internet Explore <= 8 doesn’t support some latest features of javascript which are specified in ECMAScript 5.0.

JavaScript indexof() Method

This function finds the position of given element from “string” or “array”, depends on the situation. Internet Explore 6,7,8 don’t support indexOf() method on Array while it works fine on Strings.  So, in case you have used this method for some complex array manipulation for modern browser app, it might possible you get complaint from QA team, that your javascript doesn’t works in IE8.

Implementing Array.indexOf in Internet Explore 8 (polyfill)

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (elem, startFrom) {
        var startFrom = startFrom || 0;
        if (startFrom > this.length) return -1;

        for (var i = 0; i < this.length; i++) {
            if (this[i] == elem && startFrom <= i) {
                return i;
            } else if (this[i] == elem && startFrom > i) {
                return -1;
            }
        }
        return -1;
    }
}

You could use above polyfill function to make it work in all incompatible browsers.

console.log([12, 75, 48, 30, 64].indexOf(48)); // shows 2

Use jQuery index function for Array.indexOf method

You could even use jQuery indexOf function to fix this error in incompatible browsers.

console.log(jQuery([12, 75, 48, 30, 64]).index(48)); // shows 2

Try out adhoc function (indexOf1) implementation in this fiddle – http://jsfiddle.net/vikaskbh/vb9m7/

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

 
Previous Post

How to know if HTML checkbox is checked in any version of jQuery

Next Post

Professional looking single page website using Twitter Bootstrap

Related Posts