1

This is driving me crazy... I made an array out of a "getElementsByTagName". Now, by using an onclick where the "this" method returns one of the values of that array, I cannot use "indexOf" to find its index. The console just tells me "arrayThumbs.indexOf is not a function".

This is the code:

var arrayThumbs = listThumbs.getElementsByTagName("img"); //Makes the array with the img tags

for(i=0;i<maxFiles-1;i++){
    arrayThumbs[i].onclick = function(){
        imgSelect = this; //Returns a valid value of the array, so far so good
        indexThumb = arrayThumbs.indexOf(imgSelect); //Returns an ERROR...
    };
}

The really weird part is that using the same syntax in other arrays this worked perfectly...

Thanks!

6
  • NodeList is not an array Commented Mar 8, 2016 at 18:57
  • What object is arrayThumbs actually at the point of the error? Use your browser's debugger to inspect it. Commented Mar 8, 2016 at 18:57
  • I believe that indexOf need a string value, and that imgSelect mayb don't return a string... w3schools.com/jsref/jsref_indexof.asp Commented Mar 8, 2016 at 18:59
  • 1
    @GiovanniPerillo indexOf can take anything, not just strings. Commented Mar 8, 2016 at 19:00
  • 2
    @GiovanniPerillo Note that there are 2 different .indexOf() definitions – one for Strings, one for Arrays. The latter is more-so applicable here and can accept any value. It's ability to match depends on ===, which requires the types to be the same between the argument and the values within the array. Commented Mar 8, 2016 at 19:01

1 Answer 1

4

document.getElementsByTagName returns an HTMLCollection which is "array-like" but is not an array and therefore does not have an indexOf function. To convert it to an array, you can use Array.from, if your browser supports it:

arrayThumbs = Array.from(arrayThumbs);

Or you can use a well-known trick to convert it to an array:

arrayThumbs = Array.prototype.slice.call(arrayThumbs);
Sign up to request clarification or add additional context in comments.

1 Comment

Thought the problem would be something like that... Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.