Is it possible to use indexOf (input)?

function myFunction(input){ var number_of_images = input.parentNode.getElementsByTagName("img") var image_clicked = number_of_images.indexOf(input) alert ("you clicked on image number "+image_clicked) } 

I am building a rating scale with three images. I want to tell the user which of the three images he clicked. I have onClick events on all three onClick images (this). Then I try to use indexOf (input), where input refers to the (this) parameter passed from onclick (this). This does not work. ยฟCan any alternative be offered? Thanks.

+4
source share
1 answer

Calling indexOf on it will not work, because the result is a (live) NodeList and does not provide Array methods. However, you can apply the Array indexOf method on the node list (using the .call function met ), since it is generic:

 var images = input.parentNode.getElementsByTagName("img"); var index = Array.prototype.indexOf.call(images, input); 

Note that older IEs do not support indexOf, you need to detach it .

+3
source

All Articles