1

On click, I want to target the individual parent's parent's sibling's child. There will be multiple containers. Therefore when removal is clicked I want the img in that div only to be changed.

This is the jquery I currently have - no luck am I missing an extra parent?

$('.removal').click(function() {
  $('this').parent().siblings('.item-img').find('.productImage').addClass('cart-removal-item-img')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="container">
  <div class="item-img">
    <img class="productImg" src... />
  </div>

  <div class="rndm1">
  </div>

  <div class="rndm1">
  </div>

  <div class="item-action">
    <div class="rndm1"></div>
    <p><a class="removal" href="">remove</a></p>
  </div>

</div>
Peter B
  • 22,460
  • 5
  • 32
  • 69

2 Answers2

3

When I fix two typos (quotes around 'this' and misspelled image class), I get this code working

$('.removal').on("click",function(e) {
  e.preventDefault(); // cancel the click
  $(this).closest(".container") // the container div
    .find('.productImg') // the image class in question
    .addClass('cart-removal-item-img');
});
.cart-removal-item-img { display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="container">
  <div class="item-img">
    <img class="productImg" src="http://lorempixel.com/400/200/sports/" />
  </div>

  <div class="rndm1">
  </div>

  <div class="rndm1">
  </div>

  <div class="item-action">
    <div class="rndm1"></div>
    <p><a class="removal" href="">remove</a></p>
  </div>

</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

I literally answered my own question add an extra .parent()

<script>
 $('.removal').click(function(){
        $(this).parent().parent().siblings('.item-img').find('.productImage').addClass('cart-removal-item-img')
    });
</script>
  • 1
    Just FYI, `.closest('.removal')` would be better practice than chained `parent()`. You should probably also add a `preventDefault()` call in there too as you're clicking on an `` element – Rory McCrossan Sep 08 '17 at 14:08
  • 2
    @RoryMcCrossan - closest(".container") even better ;) – mplungjan Sep 08 '17 at 14:10
  • Agreed with @RoryMcCrossan -- this sort of DOM traversal is really fragile, it'll break if you modify the DOM in seemingly innocuous ways (like adding that `

    ` tag). Much better to target elements by classname or id than by tracing a path up and down the tree...

    – Daniel Beck Sep 08 '17 at 14:12