Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing arbitrary data in HTML

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:

  • How to store arbitrary data for some HTML tags
  • Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
like image 878
Rob Colburn Avatar asked May 05 '10 09:05

Rob Colburn


1 Answers

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

like image 134
Neil Aitken Avatar answered Nov 15 '22 02:11

Neil Aitken