0

I think the solution could modifying the last line cartItems.innerHTML = cartHTML to be increasingly repeatable with the loop based on the number of the products in the cartData (based on its length). Could any one help me with this?

                for (var i = 0; i<cartData.length; i++) {
                    this["cartData"+i]=cartData[i]
                

                    let cartHTML = `
                    <tr class="cart-row">
                        <td><a href="#" type="button" class="cart-remove-button"><i class="far fa-times-circle"></i></a></td>
                        <td><img src="${cartData[i][2]}" alt=""></td>
                        <td>${cartData[i][0]}</td>
                        <td class="cart-price">DZD ${cartData[i][1]}</td>
                        <td><input class="cart-quantity-input" type="number" value="1"></td>
                        <td class="cart-sub-total">DZD ${cartData[i][1]}</td>
                    </tr>`;
                    //console.log(i)
                    **cartItems.innerHTML = cartHTML**
}

The line cartItems.innerHTML = cartHTML have to be increasingly repeatable with the loop based on the number of the products in the cartData (based on its length).

  • Does this answer your question? [Append HTML to container element without innerHTML](https://stackoverflow.com/questions/6304453/append-html-to-container-element-without-innerhtml) – freedomn-m May 15 '23 at 12:32
  • 1
    The term you're looking for is *append* (or *insert*) – freedomn-m May 15 '23 at 12:32

1 Answers1

1

With each iteration of the loop you're rewriting the cartItems innerHTML instead of adding to it.

Instead of doing this:

cartItems.innerHTML = cartHTML

You should instead do this:

cartItems.innerHTML = cartItems.innerHTML + cartHTML

Which you could rewrite as:

cartItems.innerHTML += cartHTML

Note, still, that it would probably be better to create the the HTML of the table in it's entirety and append it to the page in one go. Why? Because each time you add stuff to the page you force the browser to do a bunch of "expensive" calculations to know how to rerender the page with the new stuff you gave it.

So something like:

  const cartRows = "";

  for (var i = 0; i < cartData.length; i++) {
    this["cartData" + i] = cartData[i]


    const cartRow = `
        <tr class="cart-row">
            <td><a href="#" type="button" class="cart-remove-button"><i class="far fa-times-circle"></i></a></td>
            <td><img src="${cartData[i][2]}" alt=""></td>
            <td>${cartData[i][0]}</td>
            <td class="cart-price">DZD ${cartData[i][1]}</td>
            <td><input class="cart-quantity-input" type="number" value="1"></td>
            <td class="cart-sub-total">DZD ${cartData[i][1]}</td>
        </tr>`
      ;

    cartRows += cartRow;
  }

  cartItems.innerHTML = cartRows;
João Paulo Macedo
  • 15,297
  • 4
  • 31
  • 41