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

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

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