Sakis94
Sakis94

Reputation: 11

I want set style property from javascript variable

I am trying to do something like this:

var prop = 'width';
document.getElementById('divName').style.prop = '100px';

Upvotes: 0

Views: 150

Answers (2)

user1278767
user1278767

Reputation:

In js object properties can be accessed by two ways.

One way is using . operator if you know property name. e.g. style.width = '100px'

Second way is using square brackets [] if property name is stored in variable. e.g. prop = 'width'; style[prop] = '100px'

Upvotes: 0

adeneo
adeneo

Reputation: 318182

You can do that with bracket notation

var prop = 'width';
document.getElementById('divName').style[prop] = '100px';

Upvotes: 3

Related Questions