Storing arbitrary data in HTML
- by Rob Colburn
What is the best way to embed data in html elements for later use?
As an example, let's say we have jQuery returning some JSON from the server, and we want to dump that datat out to the user as paragraphs. However, we want to be able to attach meta-data to these elements, so we can events for these later.
The way I tend to handle this, is with some ugly prefixing
function handle_response(data) {
var html = '';
for (var i in data) {
html += '<p id="prefix_' + data[i].id + '">' + data[i].message + '</p>';
}
jQuery('#log').html(html).find('p').click(function(){
alert('The ID is: ' + $(this).attr('id').substr(7));
});
}
Alternatively, one can build a Form in the paragraph, and store your meta-data there. But, that often feels like overkill.
This has been asked before in different ways, but I do not feel it's been answered well:
http://stackoverflow.com/questions/432174/how-to-store-arbitrary-data-for-some-html-tags
http://stackoverflow.com/questions/209428/non-standard-attributes-on-html-tags-good-thing-bad-thing-your-thoughts