3

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!

Jayvan
  • 35
  • 4

1 Answers1

1

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}!`);
}));
code
  • 5,690
  • 4
  • 17
  • 39
  • 1
    or better yet use [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation#:~:text=Event%20delegation%20is%20handling%20an,on%20elements%20within%20the%20container.) on the board itself with data attributes as described in the comments above. – pilchard Jun 03 '22 at 22:48
  • 1
    @pilchard sure, but then you'd have to enter the HTML data attributes one by one. I'm trying to decide if the event delegation route enhances performance though. – code Jun 03 '22 at 22:51
  • 2
    why can't you enter the data attributes in a loop? But why would 1 listener not be more efficient than 64 listeners, or at the very least far easier to keep track of. – pilchard Jun 03 '22 at 23:03