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

Asked

Viewed 45 times

0

For example

var attr = 'background';
elemento.style.attr = 'blue';

The problem is that when I pass the second line statement, the JS understands that I seek the attribute "attr" in the style of elemento, when what I want is the "background" value that is contained in the variable attr.

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

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

1 answer

4


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

Which is also equivalent to...

var attr = 'background';
elemento['style'][attr] = 'blue';
  • I didn’t know that! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.