-1

first of all i'm talking about $('selector').data() not $.data()

now when i searched for it i found a lot of issues regarding using it

for example see this answer https://stackoverflow.com/a/8708345/2748984 it says that you can't set data with attr and get it with data (that's 4 years ago) but actually it works now but not as expected

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
        <script>
            $(function () {
                $('#testDiv').attr('data-someThing',1);
                alert($('#testDiv').data('someThing'));//alert undefined
                alert($('#testDiv').data('something'));//alert 1
                alert($('#testDiv').attr('data-something'));//alert 1
                alert($('#testDiv').attr('data-someThing'));//alert 1
            });
        </script>

    </head>
    <body>
    <div id="testDiv">test div</div>
    </body>
</html>

it's only get the lowercase version of the data name

my question is if that's intended or bug i should report to jquery

and if it's intended then why it act like that

Community
  • 1
  • 1
Robert
  • 2,342
  • 2
  • 24
  • 41

2 Answers2

2

It is not a bug as it is part of the HTML5 DOM API. It uses camelCase as it's conversion. I'll quote the DOM API again, though it was already answered here:

Does jQuery internally convert HTML5 data attribute keys to lowercase?

The custom data attributes is transformed to a key for the DOMStringMap entry with the following rules:

  • any dash (U+002D) is removed;
  • any letter following a dash (U+002D), before its removal, is set in its uppercase counterpart.

Doesn't meant that I agree with it... but so it has been written, and so it is done. :)

UPDATE

To answer your comment, you would need to rewrite the way you are setting the attribute in the first place. Change:

$('#testDiv').attr('data-someThing',1);

To:

$('#testDiv').attr('data-some-thing',1);

Community
  • 1
  • 1
Daniel C
  • 2,105
  • 12
  • 18
1

Values you are setting with attr can be retrived with data but not the other way round.

And this behaviour with the lowercase characters is intended.

The w3c specifaction says:

the name must not contain capital A to Z letters.

Reference: data-*

The reason for this behaviour is:

A custom data attribute name is transformed to a key for the DOMStringMap entry with the following rules

from MDN - dataSet

so that means you retrieve data attributes like data-foo-bar with the following:

$().data('fooBar')

Reference: get HTML 5 Data Attributes with hyphens and Case Sensitivity

However: You could use uppercase characters priot to jQuery version 1.5.

Community
  • 1
  • 1
empiric
  • 7,825
  • 7
  • 37
  • 48