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.
[].indexOfis a shorter version ofArray.prototype.indexOf.indexOfbecause it is not cross-browswer compatible. There are other, safer JavaScript methods to check for string literals, etc..match()and.test()respectively acheives what.indexOf()does and is cross-browser compatible.