Reputation: 19242
I have several outer divs, all of them contain 3 inner divs class1
class2
class3
. I want to select the outer div based on the value attribute of its inner div that has class1
. For example, I want to select the first div because its class1
div has value x
. How do I do this with jquery?
<div> <-----this is the div I want to select
<div class="class1" value="x"></div>
<div class="class2" value="y"></div>
<div class="class3" value="z"></div>
</div>
<div>
<div class="class1" value="a"></div>
<div class="class2" value="b"></div>
<div class="class3" value="c"></div>
</div>
Upvotes: 1
Views: 1428
Reputation: 23
$('div:has(.class1[value="value1"]):has(.class2[value="value2"]):has(.class3[value="value3"])');
Upvotes: 0
Reputation: 3274
You can do it so.
$(document).ready(function () {
$("div.class1 [value='x']").parent('div');
});
Upvotes: 0
Reputation: 207511
Another way is to use :has
selector
var elem = $('div:has(.class1[value="x"])');
Upvotes: 1
Reputation: 206151
$('div').has('div[value=x]');
$('div:has([value=x])').closest('div');
$('div[value=x]').parents('div');
$('div>div[value=x]').parent('div');
$.fn.getChildVal = function(val){
$('[value='+val+']').parent().css({background:'red'});
};
$('div').getChildVal('x');
From the docs:
http://api.jquery.com/closest
http://api.jquery.com/has
Upvotes: 1
Reputation: 107536
My first thought was:
$('.class1[value="x"]').parent();
But I wasn't sure of the syntax (edit: it works). This, however, could work as well:
$('.class1').filter(function() {
return $(this).attr("value") == "x";
}).parent();
Note however, these will only return the first parent (in the case of multiple child divs having a matching "value" attribute). If you want to do something with multiple parent matches, you could iterate through the result with $.each
and look at them individually:
$('.class1[value="x"]').each(function() {
var parent = $(this).parent();
});
Upvotes: 2