0

I declared some variables:

var availableTile1 = document.getElementById("c1");

var availableTile2 = document.getElementById("c2");

var availableTile3 = document.getElementById("c3");

var availableTile4 = document.getElementById("c4");

var availableTile5 = document.getElementById("c5");

var availableTile6 = document.getElementById("c6");

As you see, only the number is different. Is there a quicker and clearer way of defining all variables at once?

Note: I heard about "destructuring assignment", but I couldn't apply it with document.getElementById.6 Thank you for your answers.

EDIT: availableTile.style.border = "none"; availableTile.style.backgroundColor = "transparent";

This works if availableTile is an Id, but somehow not if it is a class?!

Mamun
  • 66,969
  • 9
  • 47
  • 59
Thurinum
  • 148
  • 3
  • 13
  • 1
    Just add a common class and get the collection by class selector – charlietfl May 06 '18 at 14:34
  • 1
    give them a class and use `document.getElementsByClassName` – Muhammad Usman May 06 '18 at 14:34
  • yes, but for some reason (I really don't know why), when I use classes my code doesn't work (see edit) – Thurinum May 06 '18 at 14:38
  • @SteelCode94 But you know that `document.getElementsByClassName` returns an `HTMLCollection` rather than a single element and that you can use the [browser console (dev tools)](https://webmasters.stackexchange.com/q/8525) (hit `F12`) to read any errors, right? – Sebastian Simon May 06 '18 at 14:40
  • yes... the console returns that the element is not defined. – Thurinum May 06 '18 at 14:43
  • @Xufox because I want each availableTile element to be a single element (so using an Id) but I have a lot (around 100) of them to declare... – Thurinum May 06 '18 at 14:45
  • @SteelCode94 Then you have to learn how to work with `document.getElementsByClassName` and `HTMLCollection`s. See the linked post for several ways. – Sebastian Simon May 06 '18 at 14:47

1 Answers1

2

Don't use variables. Do use an array. Populate it in a loop.

var available_tiles = [];
for (var i = 1; i <=6; i++) {
    available_tiles.push( document.getElementById("c" + i) );
}

You could get a similar result by changing the HTML to make every element a member of the same class. You can then get an array-like object with

var available_tiles = document.getElementsByClassName("tile");

or

var available_tiles = document.querySelectorAll(".tile");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • If using IDs instead of classes, this could be written functionally: `availableTiles = Array.from({length: 6}, (_, i) => document.getElementById("c" + (i + 1)));`. – Sebastian Simon May 06 '18 at 14:37