skip to Main Content

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


  1. I would use onClick event

    const all = document.querySelectorAll(".rgbClass");
    
    let lastClickedIndex = null;
     
    all.forEach(node => {
      node.addEventListener("click", onClick);
    });
    
    function onClick(){
      lastClickedIndex = [...all].indexOf(this);
      console.log('Last index:', lastClickedIndex);
    }
    <input name="colors[]" value="RED" type="checkbox" class="rgbClass"><br>
    <input name="colors[]" value="GREEN" type="checkbox" class="rgbClass"><br>
    <input name="colors[]" value="BLUE" type="checkbox" class="rgbClass"><br>

    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

    Login or Signup to reply.
  2. // Get all elements with rgbClass class
    document.querySelectorAll(".rgbClass").forEach(checkbox =>
        // for each element add a click event listener 
        checkbox.addEventListener('click', (event) => {
            // get the currently clicked element
            const currentCheckbox = event.currentTarget;
            // get the parent
            const parent = currentCheckbox.parentElement;
            // get the checkboxes siblings -> children of parent with rgbClass class
            const checkboxes = [...parent.childNodes].filter(element =>
                element?.classList?.contains('rgbClass') ?? false
            );
            // get the index of the current checkbox in array of all checkboxes
            const checkboxIndex = checkboxes.indexOf(currentCheckbox);
            console.log(`clicked ${checkboxIndex} index`);
        })
     );
    <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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search