In my project I am currently using some custom data-* attributes in my HTML to convey some extra data that will be used by jQuery. I found the .data()
method and noticed that if I have a data-* attribute data-my-attribute
that I can retrieve its value in jQuery by selecting the element with the attribute and calling .data("my-attribute")
.
I assumed that this was the way it is supposed to be used (did not look into the documentation) and used it through out my jQuery code. However, now I noticed that when I put for example a string "000005643"
in the HTML data-* attribute, .data("my-attribute")
return 5643
while .attr("data-my-attribute")
return "000005643"
. Where the latter is what I wanted. This led me to look up the documentation and actually found out that there is more to .data()
than I thought. Also, I never saw any text or example that indicates you should use .data()
to retrieve values of data-* attributes. This worries me that I am doing something fundamentally wrong.
So should I cease and desist with using .data()
in this manner or not? If not, could you link me to some documentation about the .data()
function that explains this use.
data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.
Second, data attributes should only be used when there are no other appropriate HTML elements or attributes. For example, it is not appropriate to store an element's class in data-class attribute. An element can have any number of data attributes with any value you want.
One way to get the value of an attribute is to use the getAttribute method available natively. We can call getAttribute to return the value of the data-fruit attribute by writing; const plant = document.
The HTML data value attribute is used to Specify the machine-readable translation of the content of the element.
The data()
method returning HTML5 data-*
attributes was introduced in 1.4.3.
As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.
Source.
It appears jQuery is certain you want a number, so it is returning a Number
for you, not the String
.
If you want it as a string, use attr()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With