Referring To A Style Property Using A Variable
In the project I am working on, I have to access the style property of an element using a variable. For example: Normally, to change the background color of an element we write
Solution 1:
Use the []
notation, eg
element.style[property] = 'blue';
Solution 2:
This is because its firing sweet error,
Uncaught SyntaxError: Unexpected string
document.getElementById("element").style
--> Style Object [object CSSStyleDeclaration]
and backgroundImage
is a property of style Object
.
To access property of style object you can use []
var property = "backgroundColor";
element.style[property] = 'blue'; // will set property of element.
Solution 3:
You can do something like :
var property = "backgroundColor" ;
element.style[property] = "blue" ;
This will let you access the background
attribute
Solution 4:
Is there a way to get var not only with style object, but also with it's value? Similar like the code below. I know this code doesn't work, i wrote it only for better explanation what i am asking.
var property = "backgroundColor = "blue" ";
element.style[property];
Post a Comment for "Referring To A Style Property Using A Variable"