I'm searching how to find the index of the element clicked in my foreach loop. Since this type of foreach loop isn't used much, I couldn't find any existing topics on this specific question.
This is my code now (css for clarity):
var toggleExtras = document.querySelectorAll(".toggle-extra");
Array.prototype.forEach.call(toggleExtras, function (toggleExtra) {
toggleExtra.addEventListener('click', function () {
console.log(index);
})
});
.toggle-extra {
background-color: #C9C9C9;
padding: 10px;
margin: 20px 0px;
color: #000;
width: 200px
}
<div class="toggle-extra">Title</div>
<div class="toggle-extra">Text</div>
<div class="toggle-extra">Button</div>
<div class="toggle-extra">Link</div>
I found the following code in another topic, which seems to work;
document.querySelectorAll("button").forEach((button, index) => {
button.onclick = (event) => {
console.log("You clicked button number " + index);
}
})
How do I use 'index' like this code in my specific foreach loop? I've tried the following without succes;
Array.prototype.forEach.call(toggleExtras, index, function (toggleExtra) {
Array.prototype.forEach.call(toggleExtras, function (toggleExtra), index {
Please don't advies me to use a different foreach method, I need to use exactly this one. Does anyone know how to do this?
function (toggleExtra, index) {