-1

I want to submit my own variable in the style object. I will show you what I mean:

var example = background
element.style.example // example is equal to the variable up top

Is there any with of doing this?

TimoStaudinger
  • 38,697
  • 15
  • 86
  • 91
Roy Berris
  • 1,310
  • 1
  • 13
  • 34

2 Answers2

1

You can use bracket notation

var example = "background";
element.style[example] = "#fff";
adeneo
  • 303,455
  • 27
  • 380
  • 377
1

Assuming you want to define the property to be set dynamically, you could use the following approach:

var example = 'background';
element.style[example] = 'black';

More on how to access object properties on MDN.

TimoStaudinger
  • 38,697
  • 15
  • 86
  • 91
  • Thank you for this fast answer, didn't know this was possible in JS. I tried `style{example}` and `style(example)` but I needed the `[ ]` – Roy Berris Nov 30 '16 at 19:42