I have an array with object that looks like this:
const boxes = [
{jsName: '.js-box1', boxName: 'upperLeft'},
{jsName: '.js-box2', boxName: 'upperCenter'},
{jsName: '.js-box3', boxName: 'upperRight'},
{jsName: '.js-box4', boxName: 'centerLeft'},
{jsName: '.js-box5', boxName: 'centerMiddle'},
{jsName: '.js-box6', boxName: 'centerRight'},
{jsName: '.js-box7', boxName: 'lowerLeft'},
{jsName: '.js-box8', boxName: 'lowerMiddle'},
{jsName: '.js-box9', boxName: 'lowerRight'}
];
.jsName refers to the class name of some div boxes.
boxName is what the new name should be when selecting them with queryselector (explained below).
I want to use a forEach loop to querySelect each .js-box and give each the name of its associated boxName.
Writing that out manually looks like this:
const upperLeft = document.querySelector(`.js-box1`);
const upperCenter= document.querySelector(`.js-box2`);
const upperRight= document.querySelector(`.js-box3`);
const centerLeft= document.querySelector(`.js-box4`);
const centerMiddle= document.querySelector(`.js-box5`);
const centerRight= document.querySelector(`.js-box6`);
const lowerLeft= document.querySelector(`.js-box7`);
const lowerMiddle= document.querySelector(`.js-box8`);
const lowerRight= document.querySelector(`.js-box9`);
I tried to use a foreach loop to store each document.querySelector inside a const called element.boxname:
boxes.forEach( (element) => {
const element.boxName = document.querySelector(`${element.jsName}`);
}
)
This returns an error with: Uncaught SyntaxError: Identifier 'element' has already been declared
2
Answers
It looks like what you really want is to create dynamic named variables.
For my answer, I created an empty object called elements. Then loop through your boxes array and add a dynamic key for each boxName set to the appropriate querySelector.
After the loop, you can just refer to them as
elements["upperLeft"], elements["upperCenter"] etc
Although not an important change, I removed the template literals from the querySelector since they aren’t needed. You have the full selector in jsName.
I think a better approach would be instead of looping over all your elements and storing their DOM elements in an object variable, Why not use a simple function that returns you DOM element instantly: