Alex Rivera | Logout

What's the best HTML attribute to use to store information for jQuery to parse?

Asked 2010-03-09T21:18:29.153
10

Must Support IE6 and must Validate vs XHTML Strict 1.0!

This is tricky to explain...

I'm using a generic class name to initiate a plugin feature on an associated element. I also want to have options associated with the element stored in an attribute as well.

<a href="url.com" class="popup" rel="900x900" >My Link</a>

With this, jQuery will look for all elements that have 'popup' and parse the rel value for the dimensions of the popup and initiate the popup() function whenever this link is clicked with a window the size w=900 h=900

but I need to take this a step further because I want to have more options...

<a href="url.com" class="popup" rel="900x900_scroll_tool_menu" >My Link</a>

I'm not sure if using the rel attribute is the place for this because I also want to use this on other elements that dont have a rel= attribute.

So I was thinking using classes for this too... I came up with this:

 <a href="url.com" class="popup opt_dim-900x900_scroll_tool_menu" >My Link</a>
 <img src="pic.gif" class="popup opt_dim-150x200_location" >My Link</a>

From the looks of this the options can get VERY long, using class seems ok, but maybe there's something better..

Which way do you think is better? Do you have another idea for this? I want to store the options in some html attribute.

Thanks!

UPDATE

I am continually reminded that there are a dozen ways to do anything in Javascript, in terms of the solutions here I later changed the correct answer to the html5 data attribute, which now that ie6 isnt an issue, seems like the best method.

Best, because it uses standard features and avoids any of the hackery I was trying to do with class names. Sure classnames are extremely flexible still, but that solution isn't

Edit
Report

1 Answer

3

I think you're looking for jQuery.data().

The jQuery.data() method allows us to attach data of any type to DOM elements ...

From the example in the link above:

var div = $("div")[0];
jQuery.data(div, "test", { first: 16, last: "pizza!" });
$("span:first").text(jQuery.data(div, "test").first);
$("span:last").text(jQuery.data(div, "test").last);
answered 2010-03-09T21:49:47.853

Your Answer