cameron cameron - 4 months ago 10
jQuery Question

jQuery onclick change html of closest div only

I need to use multiple instances of the same code snippet on the same page. This is a small image gallery, that changes out the image shown in a div based on the link clicked. I have everything working correctly, but when clicking the image to place in the div, it changes out every div on the page using that class. I tried using $(this).closest but that does not appear to be working at all. Am I close?

<div class="gallery-carousel">
<div class="galleryImageChange">
</div>
</div>
<div class="icon-pager">
<a href="#" class="imageNav"><img src="/img/logo.png"></a>
<a href="#" class="imageNav"><img src="/img/logo.png"></a>
<a href="#" class="imageNav"><img src="/img/logo.png"></a>
</div>

<div class="gallery-carousel">
<div class="galleryImageChange">
</div>
</div>
<div class="icon-pager">
<a href="#" class="imageNav"><img src="/img/logo.png"></a>
<a href="#" class="imageNav"><img src="/img/logo.png"></a>
<a href="#" class="imageNav"><img src="/img/logo.png"></a>
</div>

$('a.imageNav').click(function() {
var $content = $(this).html();
$(this).closest('div.galleryImageChange').html($content);
return false;
});


Unfortunately, I have to use multiple instances of this, and I cannot use individual ID's for each one. Here is a jsfiddle.

Answer

.closest will look for parent element of the current-element, as specified selector is not a parent of the element, nothing will be selected.

Use selector as $(this).closest('.icon-pager').prev('div.gallery-carousel').find('div.galleryImageChange')

$('a.imageNav').click(function() {
  var $content = $(this).html();
  $(this).closest('.icon-pager').prev('div.gallery-carousel').find('div.galleryImageChange').html($content);
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="gallery-carousel">
  <div class="galleryImageChange">
  </div>
</div>
<div class="icon-pager">
  <a href="#" class="imageNav">
    <img src="/img/logo.png">
  </a>
  <a href="#" class="imageNav">
    <img src="/img/logo.png">
  </a>
  <a href="#" class="imageNav">
    <img src="/img/logo.png">
  </a>
</div>

<div class="gallery-carousel">
  <div class="galleryImageChange">
  </div>
</div>
<div class="icon-pager">
  <a href="#" class="imageNav">
    <img src="/img/logo.png">
  </a>
  <a href="#" class="imageNav">
    <img src="/img/logo.png">
  </a>
  <a href="#" class="imageNav">
    <img src="/img/logo.png">
  </a>
</div>

Comments