2

If I have the following link:

<a class="camel-case" data-MyTitle="Hello">Click me</a>

And I grab the value in javascript:

var data = $('.camel-case').data();
console.log(data);

The json structure looks like this:

{
    "mytitle": "Hello"
}

Is there a way to keep the capitalization here, or does javascript (or is this within jquery?) always lowercase these?

David542
  • 104,438
  • 178
  • 489
  • 842
  • That's the `DataSet` API doing it. If you'll define your attribute as `data-My-Title` you'll get a `{ myTitle }` object (which is closer). See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset – haim770 Nov 05 '18 at 22:34
  • 6
    Possible duplicate of [Does jQuery internally convert HTML5 data attribute keys to lowercase?](https://stackoverflow.com/questions/20985204/does-jquery-internally-convert-html5-data-attribute-keys-to-lowercase) – Taplar Nov 05 '18 at 22:36
  • In general, HTML attribute names are case-insensitive. – Barmar Nov 05 '18 at 22:51

1 Answers1

3

If you insist on a PascalCase, you can try this:

<a data--My-Title="Hello">Click me</a>

Then your data() would return the following object:

{
    MyTitle: 'Hello'
}

See Fiddle

haim770
  • 48,394
  • 7
  • 105
  • 133
  • what is the suggested approach for naming in the html attributes, would it be `my_title` or `my-title` or something else? – David542 Nov 06 '18 at 17:03
  • If you want to end up with `MyTitle` as the property name, you must use `data--My-Title` as the attribute name. `data-my_title` would simply yield `my_title` and `data-my-title` yields `myTitle` – haim770 Nov 06 '18 at 19:05