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

JavascriptProperties

Javascript Problem Overview


I am using this script to make a style object of all the inherited, etc. styles.

var style = css($(this));
alert (style.width);
alert (style.text-align);

With the following, the first alert will work fine, but the second one doesn't... it's interpreting the - as a minus I assume. The debugger says 'uncaught reference error'. I can't put quotes around it, though, because it isn't a string. So how do I use this object property?

Javascript Solutions


Solution 1 - Javascript

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 become

obj["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_$]*

Solution 2 - Javascript

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);          // undefined
alert(obj['a-b']);      // 2

Solution 3 - Javascript

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).

Solution 4 - Javascript

Use brackets:

var notTheFlippingStyleObject = {
    'a-b': 1
};

console.log(notTheFlippingStyleObject["a-b"] === 1); // true

More information on objects: MDN

NOTE: If you are accessing the style object, CSSStyleDeclaration, you must use camelCase to access it from JavaScript. More information is here.

Solution 5 - Javascript

To directly answer the question: style['text-align'] is how you would reference a property with a hyphen in it. But style.textAlign (or style['textAlign']) is what should be used in this case.

Solution 6 - Javascript

alert(style.textAlign)

or

alert(style["textAlign"]);

Solution 7 - Javascript

Hyphenated style properties are referenced via camelCase in JavaScript, so use style.textAlign.

Solution 8 - Javascript

To solve your problem: The CSS properties with hyphens in them are represented by JavaScript properties in camelCase to avoid this problem. You want: style.textAlign.

To answer the question: Use square bracket notation: obj.prop is the same as obj["prop"] so you can access property names using strings and use characters that are forbidden in identifiers.

Solution 9 - Javascript

I think in the case of CSS styles they get changed to camelCase in JavaScript, so test-align becomes textAlign.

In the general case, where you want to access a property that contains non-standard characters, you use array-style: ['text-align']

Solution 10 - Javascript

The object property names are not one-to-one matches for the CSS names.

Solution 11 - Javascript

At first, I wondered why the solution didn't work on my end:

api['data-sitekey'] // Returns undefined

...later on I figured out that accessing data attributes was different:

It should be like this:

var api = document.getElementById("some-api");
api.dataset.sitekey

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDamonView Question on Stackoverflow
Solution 1 - JavascriptaustinbvView Answer on Stackoverflow
Solution 2 - JavascriptStoneyView Answer on Stackoverflow
Solution 3 - JavascriptjAndyView Answer on Stackoverflow
Solution 4 - JavascriptJoeView Answer on Stackoverflow
Solution 5 - JavascriptDawson TothView Answer on Stackoverflow
Solution 6 - JavascriptBrianView Answer on Stackoverflow
Solution 7 - JavascriptJonny BuchananView Answer on Stackoverflow
Solution 8 - JavascriptQuentinView Answer on Stackoverflow
Solution 9 - JavascriptGordonMView Answer on Stackoverflow
Solution 10 - JavascriptDoug ChamberlainView Answer on Stackoverflow
Solution 11 - JavascriptWoppiView Answer on Stackoverflow