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:
HTML5 now supports the data-name
syntax for storing abitrary data without non-standard custom attributes
This will of course break validation if your doctype is anything other than HTML5 (although there are ways around this) but it wont affect the rendering or parsing in any browsers I've come across.
Here is an excellent article by John Resig on the matter
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