Chain the class selectors, then filter based on the data parameter:
$(function() {
$("div.foo.bar").filter(function() {
return $(this).data("id") == "12345";
});
});
jsFiddle Demo
You can also easily wrap this logic into a reusable and extensible function:
function getDivWithDataId(id) {
return $("div.foo.bar").filter(function() {
return $(this).data("id") == id;
});
}
which returns the jQuery collection matching the relevant div elements.
You can extend this to include classes (by passing an array of classes, like ['foo','bar']
):
function getDivWithDataId(id, classes) {
return $("div").filter(function() {
var $self = $(this);
var classMatch = true;
$.each(classes, function(idx, val) {
if (!$self.is(val)) classMatch = false;
}
return $(this).data("id") == id && classMatch;
});
}