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

133
Vistas
Assign Target Element id to variable in JavaScript

I want to write a code in JavaScript, which will get Id of an element(in my case clicking on table. each <td> has it own id), and than using this ID I want to access corresponding element in Array. So many tries but with no success. Below is my code, please help me understand what I am doing wrong. what i can do to fix it ? :(

const items = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6],[1, 4, 7],[2, 5, 8]];
let cells = document.querySelectorAll(".cell");
function findIndex() {
  let index;
  for (let i = 0; i < cells.length; i++) {
    cells[i].addEventListener("click", function (e) {
      index = Number(e.target.id);
    });
  }
  return index;
}

console.log(items[findIndex()]);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You wrote the listener for click. Function inside the eventListener will be called only after you click on the specific table cell. Below I posted the example where after clicking I access and log into the console a corresponding value from the array.

So this is how you should access your value items[Number(event.target.id)] and pay attention that it'll be executed only after your click on the cell.

const items = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8]
];

document.querySelectorAll('.cell').forEach((currentElement) => {
  currentElement.addEventListener("click", function(event) {
    console.log(items[Number(event.target.id)]);
  })
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Solution</title>
</head>

<body>

  <table>
    <tr>
      <td id="0" class="cell">Row 1</td>
      <td id="1" class="cell">Row 2</td>
      <td id="2" class="cell">Row 3</td>
    </tr>
    <tr>
      <td id="3" class="cell">Row 4</td>
      <td id="4" class="cell">Row 5</td>
      <td id="5" class="cell">Row 6</td>
    </tr>
  </table>
</body>

</html>

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