The following line of code causes a "JScript object expected" error in IE:
hideElements.apply(window, elements);
According to IE, the 'expected JScript object' refers to hideElements
, which is a function that takes any number of HTML objects as arguments and hide them.
Concretely, I retrieve an array of HTML objects via a call to getElementsByTagName
, and I would like to pass this array as a list of arguments to the function hideElements
. The JS function apply()
is exactly what I need in that case. I know I could surely write my code differently, but since this works perfectly on Firefox and Chrome, and is technically correct, I'd really like to know why IE gets stuck there.
I've determined that, when the line is executed:
window
is not null and of type Window
;elements
is not null and of type HTMLCollection
; andhideElements
is a fully functional JS function (that works perfectly on its own and that is fully loaded when the code above is executed).getElementsByTagName
returns a nodeList
. apply
expects the second argument to be an array
. If you convert elements
to a real array (using a loop), it should work.
Note: In IE<9, it's not possible to use Array.prototype.slice.call(elements)
for that, so a loop is the safest way to create an array, like:
function nodeList2Array(nodes){
var arr = [];
for (var i=1; i<nodes.length;(i+=1)){
arr.push(nodes[i]);
}
return arr;
}
now: hideElements.apply(window, nodeList2Array(elements));
should work.