Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!