How can I get the last clicked index of NodeList using querySelector?
If:
click on "RED" checkbox returns index 0
click on "GREEN" checkbox returns index 1
click on "BLUE" checkbox returns index 2
let lastClickedIndex = document.querySelector(".rgbClass").index( ? );
document.querySelector(".rgbClass")[1].checked = true; /* GREEN will appear as checked */
<input name="colors[]" value="RED" type="checkbox" class="rgbClass">RED<br>
<input name="colors[]" value="GREEN" type="checkbox" class="rgbClass">GREEN<br>
<input name="colors[]" value="BLUE" type="checkbox" class="rgbClass">BLUE<br>
console.log(document.querySelector(".rgbClass")
):
NodeList(3) [input.rgbClass, input.rgbClass, input.rgbClass]
0: input.rgbClass
1: input.rgbClass
2: input.rgbClass
length: 3
[[Prototype]]: NodeList
2
Answers
I would use onClick event
To remember last clicked index I have used (spread)
[...all]
which converts nodelist to an array, and get index of clicked node.Then you can do whatever you want with
lastClickedIndex