Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

300
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda