How do I reference a JavaScript object property with a hyphen in it? How do I reference a JavaScript object property with a hyphen in it? javascript javascript

How do I reference a JavaScript object property with a hyphen in it?


Look at the comments. You will see that for CSS properties, the key notation is not compatible with a number of properties. Using the camel case key notation therefore is the current way:

obj.style-attr // would becomeobj["styleAttr"]

Use key notation rather than dot

style["text-align"]

All arrays in JavaScript are objects and all objects are just associative arrays. This means you can refer to a place in an object just as you would refer to a key in an array.

arr[0]

or the object

obj["method"] == obj.method

A couple things to remember when accessing properties this way:

  1. they are evaluated so use strings unless you are doing something with a counter or using dynamic method names.

    This means obj[method] would give you an undefined error while obj["method"] would not

  2. You must use this notation if you are using characters that are not allowed in JavaScript variables.

This regex pretty much sums it up:

[a-zA-Z_$][0-9a-zA-Z_$]*


The answer to the original question is: place the property name in quotes and use array style indexing:

obj['property-with-hyphens'];

Several have pointed out that the property you are interested in is a CSS property. CSS properties that have hyphens are automatically converted to camel casing. In that case you must use the camel cased name like:

style.textAlign;

However this solution only works for CSS properties. For example,

obj['a-b'] = 2;alert(obj.aB);          // undefinedalert(obj['a-b']);      // 2


CSS properties with a - are represented in camelCase in JavaScript objects. That would be:

alert( style.textAlign );

You could also use a bracket notation to use the string:

alert( style['text-align'] );

Property names may only contain characters, numbers, the well known $ sign and the _ (thanks to pimvdb).