How do I set an attribute by its name contained in a variable?

0

For example

var attr = 'background';
elemento.style.attr = 'blue';
The problem is that when I pass the second line statement, JS understands that I search for the attribute " attr " in style of elemento , when what I want is the background value that is contained in the attr variable.

I wanted the code to be interpreted like this: elemento.style.background = 'blue';

How can I get the value of the variable attr , instead of its name?

    
asked by anonymous 17.03.2017 / 03:57

1 answer

4
var attr = 'background';
elemento.style[attr] = 'blue';

Which is also equivalent to ...

var attr = 'background';
elemento['style'][attr] = 'blue';
    
17.03.2017 / 04:09