Tesla Tesla - 4 days ago 6
jQuery Question

Add a class to a grandparent's child img

I have some images with checkboxes. When I check one of them, image should change through the new class "change-img".
Here is a code:

<ul>
<li class="tech-vis"><img class="tech-img" src="..." alt="..."/></li>
<li class="check-tech"><input id="const-tech" class="checkbox-form inside" type="checkbox" name="tech[]" value="value1" /></li>
</ul>
<ul>
<li class="tech-vis"><img class="tech-img" src="..." alt="..."/></li>
<li class="check-tech"><input id="const-tech" class="checkbox-form inside" type="checkbox" name="tech[]" value="value2" /></li>
</ul>
... and etc.


And a script:

$("ul input[type=checkbox].inside").click(function() {
if($(this).is(":checked")) {
$(this).parents("ul img.tech-img").addClass("change-img");
}
else {
$("img.tech-img").removeClass("change-img")
}
});


I know that I'm wrong in line, where I'm adding a class, but how can I call this element?

Answer

Use closest() or parents() by separating the parent ul from the child img, like :

$(this).closest("ul").find('img.tech-img').addClass("change-img");
//Or
$(this).parents("ul").find('img.tech-img').addClass("change-img");

NOTE : Be careful the id should be unique in the same document.

Hope this helps.

$("ul input[type=checkbox].inside").click(function() {
  var parent = $(this).parents("ul");

  if($(this).is(":checked")) {
    parent.find('img.tech-img').addClass("change-img");
  }
  else {
    //Remove class from all img tags
    $("img.tech-img").removeClass("change-img"); 

    //Remove class from related img tag
    //parent.find('img.tech-img').removeClass("change-img"); 
  }
});
.change-img{
   background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="tech-vis"><img class="tech-img" src="http://hytorcatlantique.fr/wp-content/uploads/2014/11/android-icon.png" alt="..."/></li>
  <li class="check-tech"><input id="const-tech1" class="checkbox-form inside"  type="checkbox" name="tech[]" value="value1" /></li>                                                    
</ul>
<ul>
  <li class="tech-vis"><img class="tech-img" src="http://hytorcatlantique.fr/wp-content/uploads/2014/11/android-icon.png" alt="..."/></li>
  <li class="check-tech"><input id="const-tech2" class="checkbox-form inside"  type="checkbox" name="tech[]" value="value2" /></li>                                                    
</ul>

Comments