What is the difference in usage between $.data
and $.attr
when using data-someAttribute
?
My understanding is that $.data
The main difference between the two is where it is stored and how it is accessed.
$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.
$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user
which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.
Data set with attr()
$(element).attr('data-name')
element.getAttribute('data-name')
,data-name
also accessible from $(element).data(name)
and element.dataset['name']
and element.dataset.name
Data set with .data()
.data(name)
.attr()
or anywhere else