Variable in javascript expression

How to add a variable string to this javascript statement? where the name can match any valid string, for example WebkitTransform or Moztransform, etc.

document.getElementById('test').style.VARIABLE_NAME = 'rotate(15deg)'; 

My code doesn't seem to work when I set VARIABLE_NAME to WebkitTransform, but it works fine if I use WebkitTransform directly, since without specifying it through a variable. Thanks in advance:)

+8
javascript css3
source share
2 answers

There are two ways to access the members of a Javascript object.

Dot notation that uses an identifier to access a member:

 obj.member; 

A parenthesis designation that uses a string to access a member:

 obj['member'] 

The latter uses a string to find an element, and you can just as easily use any expression. The value of the expression will be converted to a string, so that they are equivalent:

 obj[{}] obj['[object Object]'] 

If your expression is already a string, it will be used as is, and in your case your variable contains a string that you can simply do:

 document.getElementById('test').style[VARIABLE_NAME] = 'rotate(15deg)'; 
+19
source share

There are two ways to access values ​​in javascript objects. The first is using a point operator (for example, object.memberName). The second is using the notation of a square bracket (for example, object ['memberName']).

+3
source share

All Articles