Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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}!`);
}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading