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

131
Views
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 answers
Answer question

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 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!