so i have some class-elements:
<span class="show" onclick="show()">show</span>
<span class="show" onclick="show()">show</span>
<span class="show" onclick="show()">show</span>
when i click one of these elements i need the index for some reason. i know how to use jQuery, but thats not what i am asking for, here.
my js function should look something like this:
function show() {
var index = document.getElementsByClassName('show')[??];
alert(index);
}
How is that possible with pure javascript? NOTE: i have to stick with the onclick="show()" that cannot be changed.
i hope someone can help, thanks in advance :)
If you're JUST looking for the index, you can pass that to the show() method.
You can try something like this:
addEventListener
to bind event handlers. This will allow you to usethis
.Array.indexOf
Sample
Onclick
addEventListener
If you absolutely insist on using the
onclick
attribute (even though you don't really need to):However, I would rather recommend you use delegated events to handle dynamically added elements, as using the
onclick
attribute is considered bad practice, but don't just take my word for it.The nice thing about delegated event handling is you don't need an
onclick
attribute to handle dynamically added elements, so this will work best for your particular usage.It is recommended, but not necessary, that the event listener for the delegated events is attached to the most immediate
container
of all the dynamically added elements, so that theclick
event doesn't have to bubble up all the way to thedocument.body
. This makes the handling more efficient.Just get the array of all the elements and find the current element who received the click