Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to fix Array indexOf() in JavaScript for Internet Explorer browsers?
Internet Explorer versions 8 and below don't support the Array.indexOf() method. This article shows how to fix this compatibility issue using polyfills and jQuery alternatives.
The Problem
In modern browsers, indexOf() returns the first index of an element in an array, or -1 if not found. However, IE8 and earlier throw an error when you try to use this method.
Method 1: Using Array Polyfill
Add this polyfill to support indexOf() in older IE browsers:
<!--[if lte IE 8]>
<script>
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
var len = parseInt(o.length) || 0;
if (len === 0) {
return -1;
}
var n = parseInt(fromIndex) || 0;
var k;
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in o && o[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
</script>
<![endif]-->
Method 2: Using jQuery.inArray()
jQuery provides a cross-browser alternative with jQuery.inArray():
// Syntax: jQuery.inArray(value, array [, fromIndex])
var fruits = ["apple", "banana", "orange"];
var index = jQuery.inArray("banana", fruits);
console.log(index); // Returns 1
Example: Complete Implementation
<!DOCTYPE html>
<html>
<head>
<!--[if lte IE 8]>
<script>
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var len = this.length;
var from = Number(fromIndex) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) from += len;
for (; from < len; from++) {
if (from in this && this[from] === searchElement) {
return from;
}
}
return -1;
};
}
</script>
<![endif]-->
</head>
<body>
<script>
var colors = ["red", "green", "blue"];
var position = colors.indexOf("green");
console.log(position); // Works in all browsers including IE8
</script>
</body>
</html>
Browser Compatibility Comparison
| Method | IE8 Support | Modern Browsers | Dependencies |
|---|---|---|---|
| Native indexOf() | No | Yes | None |
| Polyfill | Yes | Yes | None |
| jQuery.inArray() | Yes | Yes | jQuery library |
Conclusion
Use the polyfill method for a native JavaScript solution, or jQuery.inArray() if you're already using jQuery. Both approaches ensure cross-browser compatibility with older Internet Explorer versions.
Advertisements
