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?

1

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Such an approach also deserves much more the usage of reduce instead of forEach.
Looking at it now, I agree with you. I will change my answer.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.