0

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?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
WYZku
  • 3
  • 3
  • Related, see [Template String As Object Property Name](https://stackoverflow.com/questions/33194138/template-string-as-object-property-name). – showdev Sep 05 '21 at 17:35

2 Answers2

2

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>
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
Kenneth Lew
  • 217
  • 3
  • 7
  • Such an approach also deserves much more the usage of [`reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) instead of [`forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). – Peter Seliger Sep 05 '21 at 22:12
  • 1
    Looking at it now, I agree with you. I will change my answer. – Kenneth Lew Sep 05 '21 at 22:19
0

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.

The Otterlord
  • 1,680
  • 10
  • 20