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

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

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 Denunciar

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