Skip to content
Advertisement

How can i get a index value of a div just clicking on it?

I’m trying to change the class of an specific div that i click, using this:

JavaScript
JavaScript
JavaScript

This code above works well, but only in all divs at the same time, not with only that I’ve clicked

Advertisement

Answer

There is no need for ids and you should not use inline event attributes like onclick and instead separate your JavaScript from your HTML and use the standard .addEventListener() instead.

Also, no need for Array.prototype.forEach() as .forEach is supported on the node list returned from querySelectorAll().

To get the index, just use the index parameter that .forEach() exposes:

JavaScript
JavaScript

But, in order to change the class of the clicked element, you can just access the clicked element directly from within the event handler with the this keyword:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement