Reputation: 9183
If I have an element:
<div>
<div class="foo bar" data-id="12345"></div>
<div class="foo bar" data-id="678"></div>
<div class="foo bar" data-id="910"></div>
</div>
How can I get the element with data-id="12345"
and class="foo bar"
?
Thanks
Upvotes: 3
Views: 4820
Reputation: 18233
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;
});
}
Upvotes: 0
Reputation: 8334
If you want to access your div that has class='foo bar'
and data-id=12345
:
var element = $("div.foo.bar[data-id=12345]");
If you want simply to access the first div element that has class='foo bar' :
var element = $("div.foo.bar:nth-child(1)");
Upvotes: 1