Storing arbitrary data in HTML

Posted by Rob Colburn on Stack Overflow See other posts from Stack Overflow or by Rob Colburn
Published on 2010-05-05T09:53:39Z Indexed on 2010/05/05 9:58 UTC
Read the original article Hit count: 280

Filed under:
|
|

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:

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html