3

For the HTML DOM element -

<div style="border:1px solid; width:100px; background:#FFF" class="btn" data-btnNo="1">Button</div>

What is the difference between the two JavaScript lines below?

$(this).attr("data-btnNo");

and

$(this).data("btnNo");

According to my tests on JSFiddle, I see that the first one works, while the second does not. And I am trying to understand 'Why?'

Does jQuery maintain a separate data for each DOM elements? According to the jQuery doc of .data(), I get to understand that .data() gets the value in the HTML5 data-* into it's own data. Is the reverse true? If I do $(this).data("myData","jkl345"); will it create an HTML5 attribute data-myData="jkl345" on $(this)?

I also came across jQuery.data() that seems to extend the .data() to apply data to any DOM element.


Added Later: There seems to be an answer at jQuery Data vs Attr?. The only thing not answered there is does $(this).data("newDataAttri","myVal") create data-newDataAttri="myVal"? I am beginning to believe that it does not and only stores it in the DOM node. Can anyone confirm this?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Lord Loh.
  • 2,437
  • 7
  • 39
  • 64
  • 3
    `$(this).data("btnno");` works (all lowercase). – gen_Eric Mar 01 '13 at 17:21
  • @RocketHazmat Yes :-) You are right. I just came across http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes which mentions that `data-` should be followed by at least one character that is not A-Z. – Lord Loh. Mar 01 '13 at 17:23
  • @ManseUK - Thanks. That answers a lot of what I want to know. It did not show up on my search. I think I should have used simpler keywords. – Lord Loh. Mar 01 '13 at 17:26

1 Answers1

0

To help debug use the consoles and do console.log($('.btn').data()); You will see the object and the keys. You need to use 'btnno' lowercase 'n'

CR41G14
  • 5,464
  • 5
  • 43
  • 64
  • I had tried console.log() and it did not get me much headway. As @RocketHazmat also pointed, lower case does work :-) – Lord Loh. Mar 01 '13 at 17:29