Ryan Yiada
Ryan Yiada

Reputation: 4769

the child and parent div have the same class name, how to select the parent div?

HTML:

<div class="a" style="width:auto;....">  //I wanna add some inline-style to overwrite some stylesheet here.
  <div class="a">child</div>
  <div class="a">child</div>
</div>

<div class="a">
  <div class="a">child</div>
  <div class="a">child</div>
</div>

As you can see above , I wanna to grap the parent div's which has the same className with the child div,how can i do that?

Here is my code:

 var get_div_a = $('div.a');
 var len = get_div_a.size();
 var arr = [];

 for(var i = 0; i < len ; i++){

  if($(get_div_a[i]).children('div.a')!==0){
     ...no idea ???
  }

}

Upvotes: 1

Views: 852

Answers (2)

atredis
atredis

Reputation: 382

 var get_div_a = $('div.a');
 var len = get_div_a.size();
 var arr = [];

 for(var i = 0; i < len ; i++){

 if($(get_div_a[i]).children('div.a')!==0){
    $(this) //this is needed div
  }

 }

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173662

If you're just after filtering the nodes that have child nodes, you could do this:

$('div.a > div.a').parent()

The first expression gets all child nodes; after applying .parent() it returns the set of parent nodes (they're already filtered, i.e. no duplicates).

Upvotes: 5

Related Questions