Javascript

Joined
Jul 30, 2023
Messages
1
Reaction score
0
Guys, can you understand why I don't like the flex direction? I'm adding the image, the price and the name of the product in the cart via js, I just can't get the name of the product and the price to go one below the other

Can you please solve this problem?


 
Joined
Jul 4, 2023
Messages
479
Reaction score
60
You no need name every single div.card as card1, card2, etc. on event "click" just use that code

HTML:
<!--  onclick="addToCart(event)"  -->
<button onclick="addToCart(event)" class="add">Add</button>

and in javascript like this
JavaScript:
function addToCart(e) {
  const current_card = e.target.closest('.card');

  // ... rest of code
}

proposal to improve the javascript code (and html little bit as well ;))
[ full on-line ]

JavaScript:
function addToCart(e) {
  const current_card = e.target.closest('.card');
  const name = current_card.querySelector('.name').innerHTML,
        price = current_card.querySelector('.price').innerHTML;
 
  const name_price = document.createElement('DIV');
  name_price.classList.add('flex-name-price');
  name_price.insertAdjacentHTML('beforeend', `${price} ${name}`);
 
  const selectedItem = document.createElement('DIV'),
        img = document.createElement('IMG');
  selectedItem.classList.add('cart-img');
  img.setAttribute('src', current_card.querySelector('img').src);   
  selectedItem.append(img, name_price);
 
  const cartItems = document.querySelector('#cart');                           
  cartItems.append(selectedItem); 
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top