I need to access general information from my site using javascript. So far, I have the following options:
-
Using an html element :
<input type="hidden" value="MyValue"/> -
Using a custom attribute in an existing html element :
<div id="HtmlElement" myattr="MyValue"></div>and then access it usingdocument.getElementById("HtmlElement").getAttribute("myattr") -
Using a data attribute in an existing html element:
<div id="HtmlElement" data-myattr="MyValue"></div>and then access it usingjQuery("#HtmlElement").data("myattr")
I was wondering what are the benefits of using either option.
I’m not a fan of using hidden inputs because I don’t like the idea of having a loose html element that contains information. But since I need it to display general information, not information related to an existing html element in the page, it doesn’t seem so bad.
On the other side, I’m not a fan of abusing the use of an external library but in my case I’m allready loading jQuery in my site, so it’s not as if i was loading an entire library just for this.
And finally, even dough performance is allways an issue, in my case it’s not gonna make much difference if it’s the fastest solution.
I would go with data attributes because that’s what they are for and modern browsers have a native api for accessing them, while still allowing non-modern browsers to access them as custom attributes.
given this html:
Note if your data attribute is
data-foo-bar, the key indatasetand.datawill befooBarAs sdespont mentions, the data should be relevant to the element you are storing it on.
Update:
It’s also important to note that you can also get the value of a data attribute using the .attr method, however there is a pretty important difference between the two. Getting a data attribute’s value with .data will attempt to parse the value of the attribute into the correct javascript type, for example, if it can be converted to an int, it will be converted to an int. If it can be converted into an object or an array, it will be converted to an object or an array. If you instead used
.attr(), you can be sure that you will always have a string.Probably also worth mentioning that using
.attr()should be prefered over.data()unless you specifically need the features given by.data()due to the fact that by using.data(), a data cache will be created for that element and it’s data, which isn’t needed unless you actually intend to use.data()multiple times or need the extra features provided by.data()