So html elements can have attributes which will say something about the element. However, these attributes are visible to anyone which could be bad if the data stored is sensitive. So can you store data in/on a html element with javascript/jquery or something else?
Like (using jQuery) if I had a #apple div and wanted to append a secret data (red) to it. Could I do something with this logic?:
$("div#apple").secret = "red";
or
$("div#apple").data = { "color": "red" };
alert("The color of an apple is " + $("div#apple").secret);
I’m guessing one way to do this is create a jQuery function to bind to the html element and then bind the data to that function, but is there an easier/better way of pulling something like this off?
Also, I know that html 5 allows custom attributes, is there any version of html that allows/does the above without javascript/jquery?
Yes, jQuery’s
.data()is what you need. It stores the data in a key-value way.You can use it in this way:
And then you can retrieve it in this way:
It works storing all the data you what in its internal object
jQuery.cache.