Home > Back-end >  Append elements with the same class to multple divs that also share a class
Append elements with the same class to multple divs that also share a class

Time:11-11

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 >
      <div >
        <img>
      </div>
      <div >
        <a >Add to cart</a>
      </div>
    </li>
    <li >
      <div >
        <img>
      </div>
      <div >
        <a >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?

CodePudding user response:

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 >
      <div >
        <img>Product 1
      </div>
      <div >
        <a >Add to cart</a>
      </div>
    </li>
    <li >
      <div >
        <img>Product 2
      </div>
      <div >
        <a >Add to cart</a>
      </div>
    </li>
    <ul>
</div>

  • Related