I try to get index from array of elements.
var arr = document.getElementsByClassName('class'); //3 elements
console.log(arr);
output// [div.class.selected, div.class, div.class, item: function, namedItem: function]
var selected = document.getElementsByClassName('selected');
var selected_id = arr.indexOf(selected[0]);
The last line of code give me an error Uncaught TypeError: undefined is not a function.
I also tried to add toString() and search, but the same error.
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);
<div class="class"></div><div class="class"></div><div class="class selected"></div><div class="class"></div>
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().If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With