1

I have an array that contains HTML elements(I filled it with querySelectorAll()), and I'm trying to find the index of an element in that array but the console is giving the error:

Uncaught TypeError: rows.indexOf is not a function

I used this to fill the array with the needed HTML elements:

rows = document.querySelectorAll("#selectableTableBody > tr");

and this to find the index:

document.getElementById("tableItem_10087528").onclick = function (e) { console.log(rows.indexOf(this)); }

and here is an image of my test in the console(which doesn't make sense): image captured from Chrome's console

it's worth noting that these elements are generated with javascript and then put in the array using querySelectorAll() here is a jsfiddle if you want to check the whole thing

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
ELIAS YOUSSEF
  • 69
  • 4
  • 11

4 Answers4

3

I have an array that contains HTML elements(I filled it with querySelectorAll())

No, you don't, which is the problem. :-) querySelectorAll returns a NodeList (MDN | spec), not an array.

You can convert it into an array in several ways:

rows = Array.from(document.querySelectorAll(/*...*/));

or (in up-to-date environments where NodeList is iterable):

rows = [...document.querySelectorAll(/*...*/)];

or in old environments:

rows = Array.prototype.slice.call(document.querySelectorAll(/*...*/));

Re iterability: This answer discusses polyfilling NodeList iterability on platforms where arrays are iterable (either natively or thanks to a polyfill) but NodeList isn't (yet).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Uncaught TypeError: rows.indexOf is not a function

You get this error because you are calling .indexOf() over a nodeList and not an array, because document.querySelectorAll() will return a nodeList and not an array.

You can get an array from this nodeList/collection using Array.from() method:

rows = Array.from(document.querySelectorAll("#selectableTableBody > tr"));

Demo:

This is your updated fiddle.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

querySelectorAll returns NodeList, not an array.

You need to use

rows = Array.from(document.querySelectorAll("#selectableTableBody > tr"));
Nikita Skrebets
  • 1,518
  • 2
  • 13
  • 19
1

That is bacause the return of querySelectorAll() is an array like object (object with length property) not an array. you need to convert it to array using Array.from(rows).

Tarek Essam
  • 3,602
  • 2
  • 12
  • 21