Javascript – How to store arbitrary data for some HTML tags

htmljavascript

I'm making a page which has some interaction provided by javascript. Just as an example: links which send an AJAX request to get the content of articles and then display that data in a div. Obviously in this example, I need each link to store an extra bit of information: the id of the article. The way I've been handling it in case was to put that information in the href link this:

<a class="article" href="#5">

I then use jQuery to find the a.article elements and attach the appropriate event handler. (don't get too hung up on the usability or semantics here, it's just an example)

Anyway, this method works, but it smells a bit, and isn't extensible at all (what happens if the click function has more than one parameter? what if some of those parameters are optional?)

The immediately obvious answer was to use attributes on the element. I mean, that's what they're for, right? (Kind of).

<a articleid="5" href="link/for/non-js-users.html">

In my recent question I asked if this method was valid, and it turns out that short of defining my own DTD (I don't), then no, it's not valid or reliable. A common response was to put the data into the class attribute (though that might have been because of my poorly-chosen example), but to me, this smells even more. Yes it's technically valid, but it's not a great solution.

Another method I'd used in the past was to actually generate some JS and insert it into the page in a <script> tag, creating a struct which would associate with the object.

var myData = {
    link0 : {
        articleId : 5,
        target : '#showMessage'
        // etc...
    },
    link1 : {
        articleId : 13
    }
};

<a href="..." id="link0">

But this can be a real pain in butt to maintain and is generally just very messy.

So, to get to the question, how do you store arbitrary pieces of information for HTML tags?

Best Answer

Which version of HTML are you using?

In HTML 5, it is totally valid to have custom attributes prefixed with data-, e.g.

<div data-internalid="1337"></div>

In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain about it, but in 1.0 mode, most browsers will just silently ignore it.

If I were you, I would follow the script based approach. You could make it automatically generated on server side so that it's not a pain in the back to maintain.