rails and html data attributes: use dash(-) or underscore(_)?

benams picture benams · Mar 5, 2013 · Viewed 10.4k times · Source

Lately, I'm facing problems with HTML custom data attributes in my rails application. I user the following pattern in order to add some data attributes to the html tags and use them later in my javascript(jQuery) code:

= %a.name{ href: "url.com", data: {first_name: "ben", last_name: "amsalem} }

In the javascript code I access those attributes:

alert($(".name").data("first_name") + " " + $(".name").data("last_name"));

In my development environment it goes well and I get the expected result (the same is true for my production environment in the past), but in my current production version I get "undefined" values. I checked the HTML source of the page and I saw that I now have something like:

<a class="name" href="url.com" data-first-name="ben" data-last-name="amsalem" />

Instead of:

<a class="name" href="url.com" data-first_name="ben" data-last_name="amsalem" />

Why does it happen? What causes the change?

Answer

Robin picture Robin · Mar 5, 2013

It's perfectly normal, data: { first_name: "ben" } is supposed to produce data-first-name="ben".

The best way you would access this attribute is with .data("firstName"), but .data("first-name") would also work.