TooWarmInFebruary
TooWarmInFebruary

Reputation: 151

Applying styles in javascript with a for-in loop

So I have an object full of key-value pairs that describe the intended style of an element and I am trying to apply that style to an element by looping through the object like this:

element = document.createElement('div');   
style = {width : '220px', height : '100%', left : '0', height : '0', position : 'relative'}
for (x in style){
    element.style.x = style[x];
}

And yet the element remains without a style. This seems so simple that I cannot figure out what might be going wrong,so I assume I am missing something incredibly obvious. Thank you for any help you can provide.

Upvotes: 1

Views: 706

Answers (2)

Jeremy
Jeremy

Reputation: 22415

You are setting the property x on each iteration. Instead, use the value of x like so:

element.style[x] = style[x];

Upvotes: 4

jfriend00
jfriend00

Reputation: 707318

Change to this:

element = document.createElement('div');   
style = {width : '220px', height : '100%', left : '0', height : '0', position : 'relative'}
for (x in style){
    element.style[x] = style[x];
}

Upvotes: 0

Related Questions