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

136
Vistas
Declare multiple document.getElementById(''); variables in few lines

I am making a chess game as a fun project. The way I have it set up involves one variable per square, which is taking me 64 lines of code as of right now.

The variable name should be the same as the ID.

My current code:

const a1 = document.getElementById('a1');
const a2 = document.getElementById('a2');
const a3 = document.getElementById('a3');
const a4 = document.getElementById('a4');
const a5 = document.getElementById('a5');
const a6 = document.getElementById('a6');
const a7 = document.getElementById('a7');
const a8 = document.getElementById('a8');

(goes on for 7 more sets of 8)

I have not tried anything else yet because I'm not sure where to start.

Are there any methods to shorten this? Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

To directly answer your question: Use a loop and add all the data to an array:

const board = [...new Array(64)].map((_, i) => document.getElementById("a" + i));

And you can access each element like:

board[3];
board[32];

and so on, but I would never structure my HTML that way with so many IDs.

A better way would be to just query the parent element and get its children, something like:

<div id="board">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  ...
</div>

Then in your JavaScript you could do:

const board = document.getElementById("board").children;

and boom, it's all set up for you:

board[0];
board[77];
board[5];
// yay

// e.g. listen for clicks on any square
board.forEach((square, i) => square.addEventListener("click", e => {
  console.log(`You clicked square #${i}!`);
}));
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