Difference between $.data('foo') and $.attr('data-foo') in jQuery
10 June 2012
I learned something today thanks to my colleague Axel Hecht; the difference between
.data() getter/setter is more powerful since it can do more things. For example:
<img id="image" data-number="42">
// numbers are turned to integers assert($('#image').data('number') + 1 == 43); // the more rudimentary way assert($('#image').attr('data-number') + 1 == '421');
Integers is just one thing the
.data() getter is able to parse. It can do other cool things too like booleans and JSON. Check out its docs
So, why would you NOT use
One reason is that with
data- attribute further along in the page rendering process.
To see it in action check out: test.html
In conclusion: just be aware of it. Feel free to use the
.data() getter/setter because it's way better but be aware of the potential risks.