Coder Perfect

For some HTML tags, how can I save arbitrary data?


I’m working on a page that uses javascript to provide some interaction. As an example, links that make an AJAX request to retrieve article material and then display it in a div. In this case, I obviously need each link to contain an extra bit of data: the article’s id. In case it comes up again, I’ve started putting the information in a href link like this:

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

After that, I use jQuery to locate the a.article elements and apply the proper event handler. (Don’t get too worked up over usability or semantics; this is only an example)

Anyway, this method works, but it stinks a little and isn’t very extendable (what if the click function has many parameters?). What if some of those options aren’t required?)

The obvious solution was to apply attributes to the element. I mean, isn’t that what they’re for? (In a way.)

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

I recently questioned if this method was valid, and it turns out that it is not valid nor trustworthy unless I define my own DTD (which I don’t). A typical answer was to put the data in the class attribute (though this could be due to my poor example selection), but this smells much worse to me. 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