Search code examples
javascriptjqueryjquery-selectors

On click find element and open nearest modal window


I'm having trouble finding an element relative to a button when clicked.

For some context I'm looping through products. Each product has its own modal window so I want to be able to open the modal window relative to the product when clciking a button with the class name .quick-cart.

This is the JS I have to try and do this:

$('.quick-cart').click(function() {
  var modal = $(this).parent('.product-item').siblings().find(".md-modal");
  $(modal).addClass('md-show');
  $('.md-overlay').addClass('show');
  $('html,body').addClass('no-scroll');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product">
  <div class="product-item">
    <div class="product-item-container">
      <div class="product-item-show-scroll">
        <div class="product-item__content">
          <h3>Title</h3>
          <div class="product-item__img">
            <img src="#">
          </div>
        </div>
      </div>
      <div class="product-item-under-scroll">
        <div class="btn__group">
          <button class="quick-cart">Quick Cart</button>
        </div>
      </div>
    </div>
    <div class="product-item__bottom">
      <p class="price">Price</p>
    </div>
  </div>
  <div class="md-modal">
    Modal content for product
  </div>
</div>


Solution

  • You don't really need siblings and find. next will do

    var model = $(this).closest('.product-item').next(".md-modal");