0

need to reference 5 boxes for my JS script soo I add them using querySelector like soo:

var box0 = document.querySelector(".box1");
var box1 = document.querySelector(".box2");
var box2 = document.querySelector(".box3");
var box3 = document.querySelector(".box4");
var box4 = document.querySelector(".box5");

It works but I was wondering it it was possible to use a loop that would concatenate an i variable to "box" for each cicle using toString() maybe..

I have no idea how it would work but what I want is this:

for(i=0;i<5;i++){
var "box + i" = ... (".box + i")
}
OryxGD
  • 1
  • 2
  • 4
    Use an object or an array. No reason to create variables. Give the elements a common class and let querySelectorAll put them into an array – epascarello Jul 27 '22 at 20:33
  • 1. use an array 2. don't have one class for each thing. If you want to handle them the same, then just give them `.box` and apply the same rules to all. If they should be treated *differently*, then there is really no reason to make them superficially seem similar by numbering them. – VLAZ Jul 27 '22 at 20:36
  • @epascarello I can't find anything online about that. Not sure how I would do it either. – OryxGD Jul 27 '22 at 20:36
  • 1
    The best solution depends on what you are doing with it. 99.99% of the time what you want is not the way to do it. – epascarello Jul 27 '22 at 20:38
  • `let boxes = document.querySelectorAll('[class^="box"]')` will return a static NodeList of elements that have a class value starting with "box". – RobG Jul 28 '22 at 03:43

0 Answers0