Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Array.prototype.slice: 'this' is not a JavaScript object" error in IE8

It is my understanding that IE8 has access to the Array.prototype.slice method. Yet when I try to call it to turn a NodeList into an array, it gives me the error Array.prototype.slice: 'this' is not a JavaScript object. You can check it out here, or look at my code here:

HTML

<div id="test">Test</div>

JavaScript

var divs = document.getElementsByTagName('div');
divs = Array.prototype.slice.call(divs);
console.log(divs);

What's going on here?

like image 444
Aust Avatar asked Nov 09 '12 23:11

Aust


2 Answers

Update: A NodeList can be treated as an array in some ways - you don't actually have to do anything special with it before you can loop over it, for example:

var aDivs = [];
for (var = i = 0; i < divs.length; i++) {
    aDivs.push(divs[i]);
}

This will create an array with all of the nodes that matched when you ran document.getElementsByTagName()

See this question for a full explanation of why slice works with a NodeList in some browsers but not others, but it boils down this this sentence from the specification:

Whether the slice function can be applied successfully to a host object is implementation-dependent.

like image 109
Kelvin Avatar answered Nov 17 '22 11:11

Kelvin


The error message is accurate - your nodelist is not a JavaScript object, it is a "Host Object", which you can't necessarily pass around like regular JavaScript objects. Run this code in IE8's JavaScript console:

document.querySelectorAll("div") instanceof Object

It returns false.

like image 2
gilly3 Avatar answered Nov 17 '22 11:11

gilly3