58

I have the following code:

alert($embellishment.data("embellishmentId"));
alert($embellishment.attr("data-embellishmentId"));

The first alert returns undefined, whereas the second alert returns an integer, 3.

-- SEE DEMO --

I'm using jQuery version 1.7.2 (data was added with version 1.4 I believe)

Why is this? Should I be using data() at all if its not returning the right values?

Curtis
  • 101,612
  • 66
  • 270
  • 352

1 Answers1

121

OK. I found the problem by interpreting jQuery docs.

When you write:

$embellishment.data("embellishmentId");

it is handled by jQuery as compound attribute:

<div data-embellishment-id="3"></div>

So, to solve the problem you can use lower case in the data key otherwise it just addresses the different attribute.

<!-- HTML -->
<div data-embellishmentid="3"></div>

// JavaScript
$embellishment.data("embellishmentid");
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 7
    Here is the source code that does it: `var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();` in internal function `dataAttr`. Where `rmultidash` is `rmultiDash = /([A-Z])/g;` – Esailija Jun 12 '12 at 08:46
  • http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#embedding-custom-non-visible-data-with-the-data-*-attributes – Alex Jun 12 '12 at 08:46
  • Guys, jQuery has done that for a long time. Take a look at CSS attributes. If you want to see a CSS style, it uses camelCase for un-quoted attributes. For example: `$('#elem').css({paddingTop: '40px'});` and `$('#elem').css({'padding-top': '40px'});`. – TerranRich Dec 09 '14 at 16:44
  • @Vision, If we use multiple data how it's works? eg
    ,
    ,
    – Sarath TS Sep 03 '15 at 11:07
  • @samsam Not sure what you ask for, but assume you want an array of values. Use this approach: `$embellishment.map(function() { return $(this).data('embellishmentid'); }).get();`. – VisioN Sep 04 '15 at 10:16