jquery data selector

Posted by Tauren on Stack Overflow See other posts from Stack Overflow or by Tauren
Published on 2010-05-23T11:08:17Z Indexed on 2010/05/23 11:10 UTC
Read the original article Hit count: 446

Filed under:
|

I need to select elements based on values stored in an element's .data() object. At a minimum, I'd like to select top-level data properties using selectors, perhaps like this:

$('a').data("category","music");
$('a:data(category=music)');

Or perhaps the selector would be in regular attribute selector format:

$('a[category=music]');

Or in attribute format, but with a specifier to indicate it is in .data():

$('a[:category=music]');

I've found James Padolsey's implementation to look simple, yet good. The selector formats above mirror methods shown on that page. There is also this Sizzle patch.

For some reason, I recall reading a while back that jQuery 1.4 would include support for selectors on values in the jquery .data() object. However, now that I'm looking for it, I can't find it. Maybe it was just a feature request that I saw. Is there support for this and I'm just not seeing it?

Ideally, I'd like to support sub-properties in data() using dot notation. Like this:

$('a').data("user",{name: {first:"Tom",last:"Smith"},username: "tomsmith"});
$('a[:user.name.first=Tom]');

I also would like to support multiple data selectors, where only elements with ALL specified data selectors are found. The regular jquery multiple selector does an OR operation. For instance, $('a.big, a.small') selects a tags with either class big or small). I'm looking for an AND, perhaps like this:

$('a').data("artist",{id: 3281, name: "Madonna"});
$('a').data("category","music");
$('a[:category=music && :artist.name=Madonna]');

Lastly, it would be great if comparison operators and regex features were available on data selectors. So $(a[:artist.id>5000]) would be possible. I realize I could probably do much of this using filter(), but it would be nice to have a simple selector format.

What solutions are available to do this? Is Jame's Padolsey's the best solution at this time? My concern is primarily in regards to performance, but also in the extra features like sub-property dot-notation and multiple data selectors. Are there other implementations that support these things or are better in some way?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-selectors