bethro
bethro

Reputation: 53

How can I include a Javascript style attribute into a variable without redefining the variable?

I am trying to make my very own package and I am trying to reduce the lines of code that I have, the example below is a close reflection of what I am doing but I have 25 more switch statements and I am tried that I have to re-type something like break(nothing I can do about it) but surely there is a way I can place btn.style.backgroundColor inside a variable without redefining the variable? cause this will really help me alot.

var i = 0; 
arr = ['black','red','yellow', 'green'];  
document.querySelectorAll('button').forEach(function(btn) {
 arr.forEach(function(){                
           switch(arr[i]) {
           case "black":
           btn.style.backgroundColor = 'grey';
           break;
           case "yellow":
            btn.style.backgroundColor = 'red'; 
           break; 
           case "red": 
           btn.style.backgroundColor ='yellow'; 
           break;
           case "green": 
           btn.style.backgroundColor ='lime'; 
           break; 
           default: 
           btn.style.backgroundColor ='aqua'   
       }}) 
  i++
})
<button>click me</button>
<button>click me</button>
<button>click me</button>
<button>click me</button>
<button>click me</button>

Upvotes: 0

Views: 63

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28206

It seems to me you can achieve what you want much easier:

const arr = ['grey','yellow','red','lime'];  
[...document.querySelectorAll('button')]
  .forEach((btn,i)=>btn.style.backgroundColor = arr[i] || 'aqua')
<button>click me</button>
<button>click me</button>
<button>click me</button>
<button>click me</button>
<button>click me</button>

As the original colours in your "key"-array were never used I simply left them out and used the array arr instead to hold the background colours.

Upvotes: 1

Mario Vernari
Mario Vernari

Reputation: 7306

You use the outer forEach correctly, but the inner wrongly. Check the inner function argument: that's the element of the arr array:

arr = ['black','red','yellow', 'green'];  
document.querySelectorAll('button').forEach(function(btn) {
arr.forEach(function(a){                
           switch(a) {
           case "black":
           btn.style.backgroundColor = 'grey';
           break;
           case "yellow":
            btn.style.backgroundColor = 'red'; 
           break; 
           case "red": 
           btn.style.backgroundColor ='yellow'; 
           break;
           case "green": 
           btn.style.backgroundColor ='lime'; 
           break; 
           default: 
           btn.style.backgroundColor ='aqua'   
       }}) 
})

Upvotes: 1

Related Questions