Search code examples
javascripthtmldom

How to get index of an array element in click event with JavaScript


I'm developing an Electron App, and for this specific part of the code, it's necessary that I recover the index of the current element (on click).

HTML:

<div>
    <input type="checkbox" class="optionBox"> Minimize to tray after 10 seconds
    <input type="checkbox" class="optionBox"> Always check day transition
</div>

JavaScript:

modifierCheckboxes = document.querySelectorAll('.optionBox');

for (var i = 0; i < modifierCheckboxes.length; i++) {
    modifierCheckboxes[i].addEventListener('click', function (e) {
        bindModifierCheckBoxes(e);
    });
}

function bindModifierCheckBoxes(e) {
    // I need the reference for modifierCheckboxes[i] here 
}

I've tried this:

function bindModifierCheckBoxes(e){
    var t=e.target;
    console.log(Array.prototype.indexOf.call(t.parentNode.childNodes,t));
}

It came "close", but when I click on the first checkbox, I get index of 1, and in the second one I get 3.

Please, no external libraries, just plain JavaScript.


Solution

  • Maybe you can convert the Object selector to an array and then you can use an indexOf.

    var checks = document.querySelectorAll('.optionBox');
    
    checks.forEach(function(check){
      check.addEventListener('click', checkIndex);
    })
    
    function checkIndex(event){
      console.log( Array.from(checks).indexOf(event.target) );
    }