Home > Enterprise >  loop elements in array jQuery
loop elements in array jQuery

Time:11-12

Sorry for my bad english but,

I'm trying to loop all children elements in array but it keeps looping only the first element however how much elements inside the parent

$(".js-drawer-open-cart").on("click", function (event) {
  var items = [];

  $(".cart__items .cart__item").each(function () {
    let product_title = $(".cart__item--name").attr("data-product-title");
    let product_id = $(".cart__item--name").attr("data-product-id");
    let product_variant = $(".cart__item--name").attr("data-product-variant");
    let product_quantity = $(".cart__item--name").attr("data-product-quantity");
    let product_price = $(".cart__item--name").attr("data-product-price");

    dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
    var item = {};

    item.item_name = product_title;
    item.price = product_price;
    item.item_brand = "El grande Porto";
    item.item_variant = product_variant;
    item.quantity = product_quantity;

    
    items.push(item);
  
  });

  dataLayer.push({
    event: "view_cart",
    ecommerce: {
      items: items,
    },
  });

});

CodePudding user response:

$(".cart__items .cart__item").each iterates over all the elements that match the given selector, not the children of that element. If there should only be one match, try taking the first element and looping over its children?

Example: $(".cart__items .cart__item").first().children().each

CodePudding user response:

It works for me thanks to epascarello's answer :

All i had to do is this :

$(this).find(".cart__item--name").attr("data-product-title");
  • Related