Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOf element in array [duplicate]

Tags:

javascript

dom

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.

like image 230
RaShe Avatar asked Sep 15 '26 15:09

RaShe


1 Answers

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().
like image 70
David Thomas Avatar answered Sep 17 '26 04:09

David Thomas