Search code examples
javascriptjqueryappendcode-snippets

Append elements with the same class to multple divs that also share a class


I'm setting up a store catalog in which I have a div with multiple list items containing 2 divs (one for picture and another one for product summary and add to cart button)

Structure would be something like this.

<div>
  <ul>
    <li class="product">
      <div class="product-image">
        <img>
      </div>
      <div class="product-summary">
        <a class="button">Add to cart</a>
      </div>
    </li>
    <li class="product">
      <div class="product-image">
        <img>
      </div>
      <div class="product-summary">
        <a class="button">Add to cart</a>
      </div>
    </li>
  <ul>
</div>

I want to move the Add To Cart button to the div that contains the image. I tried with this jQuery

jQuery(document).ready(function(){
 jQuery(".product-image").append(jQuery('.button'));
});

But this adds every sigle button to the image div, and I end up with 10+ add to cart buttons on every product. Is there any way to only move the button within each li element to its respective image div?


Solution

  • Use a .each() loop and then move the button with the same index.

    let buttons = $(".button");
    
    $(".product-image").each(function(i) {
      $(this).append(buttons.eq(i));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      <ul>
        <li class="product">
          <div class="product-image">
            <img>Product 1
          </div>
          <div class="product-summary">
            <a class="button">Add to cart</a>
          </div>
        </li>
        <li class="product">
          <div class="product-image">
            <img>Product 2
          </div>
          <div class="product-summary">
            <a class="button">Add to cart</a>
          </div>
        </li>
        <ul>
    </div>