I want to loop through an array and give their name. I tried to use template literals, but it doesn't work.
const colors = ['yellow', 'green', 'brown', 'blue', 'pink','black']
for (let color of colors){
const `${color}Button` = document.querySelector(`#${color}`);
}
the results I want should be something like this
yellowButton = document.querySelector(#yellow);
greenButton = document.querySelector(#green);
.
.
.
.
blackButton = document.querySelector(#black);
Could you guys please revise my code?
CodePudding user response:
You can attach variables onto the window object, making it accessible as a global variable. However this is a bad practice, since it pollutes namespace, causing unnecessary bugs and much headache in the future. A much better approach to this is to use native javascript objects, as this is the exact use case it was made for.
With your example:
const colors = ['yellow', 'green', 'brown', 'blue', 'pink', 'black']
const buttons = colors.reduce((accum, color) => {
accum[`${color}Button`] = document.querySelector(`#${color}`);
return accum;
}, {});
console.log(buttons)
// to access certain element:
const elem = buttons.yellowButton
console.log(elem)
<button id='yellow'></button>
<button id='green'></button>
<button id='brown'></button>
<button id='blue'></button>
<button id='pink'></button>
<button id='black'></button>
CodePudding user response:
In the browser, you can attach variables to the window interface and reference them as if they were defined in the global scope.
for (const color of colors) {
window[`${color}Button`] = document.querySelector(`#${color}`)
}
console.log(redButton.textContent)
However, as others have mentioned, it may not be the best approach.