I was wondering if there\'s a way to select an item (div,span,whatever..) using javascript with jQuery (+ jQuery UI lib) based on its data attribute value. For example, let\
var resultingElement = $('.b[data-myKey=1234]');
I'm not sure 100% sure, but I think there was an issue with camel-case selectors in data attributes at some point.
You can create a custom pseudo-selector to make things easy: http://jsfiddle.net/g2xKB/1/.
$.expr.pseudos.data = $.expr.createPseudo(function(args) {
var items = args.split(","); // the arguments (key, value)
$.each(items, function(i, item) {
item = item.trim();
var isString = /^['"]|['"]$/.test(item);
item = item.replace(/^['"]|['"]$/g, ""); // remove quotes
if(!isString) {
item = +item; // if no quotes, it's a number
}
items[i] = item;
});
return function(elem) {
return $.data(elem, items[0]) === items[1];
}
});
You can then use it as follows:
$(".b:data('myKey', 1234)").css("color", "red");
Try this
$("div.b").filter(function() {
return $.data(this, "myKey") == 1234;
});