robert robert - 11 months ago 42
jQuery Question

jquery data not working as expected

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 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>
<script src=""></script>
$(function () {
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

<div id="testDiv">test div</div>

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


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:


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

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