I want to display the index (number) of each child when i click it

Viewed 38

Here I have a parent which contains a few children. I want to display the index (number) of each child on the console by clicking on it. i tried to use forEach method to detect the clicked child, but when i try to get the index of the child that i clicked it does not work. I tried indexOf() method but it shows an error

let parent = document.querySelector('.parent');
let children = document.querySelectorAll('.child');
children.forEach(child => {
    child.onclick = function () {
      console.log( /* children.indexOf(child) */ ) 
      // this is the method i tried but it didn't worked
     
      console.log( /*here i want to display the index of the clicked child */ );
    }
});
<div class="parent">
    <div class="child">a</div>
    <div class="child">b</div>
    <div class="child">c</div>
    <div class="child">d</div>
</div>

1 Answers

You just need to convert children from a NodeList into an array (using Array.from) to use indexOf:

let parent = document.querySelector('.parent');
let children = document.querySelectorAll('.child');
children.forEach(child => {
    child.onclick = function () {
      console.log(Array.from(children).indexOf(child));
    }
});
<div class="parent">
    <div class="child">a</div>
    <div class="child">b</div>
    <div class="child">c</div>
    <div class="child">d</div>
</div>

Related