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

101
Views
How to index coordinates of elements in a matrix

I am drawing a two-dimensional matrix with vanilla JavaScript and CSS, but I'm struggling to index coordinates of every element.

There are a couple of problems. If I put coordinates in class, for example,

class="_1 _2"

And then use either getElementsByClassName or querySelector, I will get both elements with class="_1 _2" and class="_2 _1"

My current solution is to use both class and id. I then reference with document.getElementsByClassName("_1")[1]

I wonder if you have any thought/suggestion about this?

Thank you

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

0

Guess you could use data attributes like so:

const elements = document.querySelectorAll('[data-x="2"][data-y="1"]');

for (let el of elements) {
    el.classList.add('selected');
}
table td {
  width: 50px;
  height: 50px;
  margin: 2px;
  background-color: green;
  color: white;
}

.selected {
  background-color: red;
}
<table>
  <tr>
    <td data-x="1" data-y="1">11</td>
    <td data-x="1" data-y="2">12</td>
  </tr>
  <tr>
    <td data-x="2" data-y="1">21</td>
    <td data-x="2" data-y="2">22</td>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Report

0

Do you actually want to give them all named classes?

It is sometimes easier to use the position of elements - nth-child(1) for example - in this sort of situation as they can be accessed via integer calculations rather than having to make a string (or two) to match the classes.

Here's a trivial example:

function getEl(mx, row, column) {
  return mx.querySelector(':nth-child(' + (row - 1) * 2 + column + ')');
}
const matrix = document.querySelector('#matrix');
alert(getEl(matrix, 1, 2).innerHTML);
#matrix div:nth-child(odd) {
  background: green;
}
<div id="matrix">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>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!