It's because arr
is a (live) NodeList not an array; what you want is, I think:
console.log([].indexOf.call(arr, selected[0]));
var arr = document.getElementsByClassName('class');
var selected = document.getElementsByClassName('selected');
var selected_id = [].indexOf.call(arr, selected[0]);
console.log(selected_id);
The line:
var selected_id = [].indexOf.call(arr, selected[0]);
Uses the native Array.prototype.indexOf()
method, supplying the arr
as the this
(basically using arr
as the array on which the method is called), supplying selected[0]
as the argument to be passed to the method, so it sort of gets applied as you called it yourself:
var selected_id = arr.indexOf(selected[0]);
but does it in a way that recognises the indexOf()
method isn't available to the NodeList
object (calling it in a legitimate way, and therefore preventing the error).
References:
- Array.prototype.indexOf().
- document.getElementsByClassName().
- Function.prototype.call().