Question

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>
Was it helpful?

Solution

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();
});

OTHER TIPS

$('div').has('div[value=x]');

demo

$('div:has([value=x])').closest('div');

demo 2

$('div[value=x]').parents('div');

demo 3

$('div>div[value=x]').parent('div');

demo 4

$.fn.getChildVal = function(val){  
  $('[value='+val+']').parent().css({background:'red'});
};

$('div').getChildVal('x'); 

plugin :)

From the docs:

http://api.jquery.com/closest
http://api.jquery.com/has

Another way is to use :has selector

var elem = $('div:has(.class1[value="x"])');

You can do it so.

           $(document).ready(function () {
            $("div.class1 [value='x']").parent('div');
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top