Here is a short product list for the reference. I would like to have my gtag generated below the product list. How can I do this?
<div class="product">
<div class="name">Audi</div>
<div class="price">21.000</div>
</div>
<div class="product">
<div class="name">Opel</div>
<div class="price">17.000</div>
</div>
<div class="product">
<div class="name">Cadillac</div>
<div class="price">33.500</div>
</div>
Here I need all the product values in the items parts.
<script>
gtag("event", "view_item_list", {
item_list_id: "category_products",
item_list_name: "Products from a category",
items: [
{
item_name: "Audi",
price: 21.000,
index: 0
},
{
item_name: "Opel",
price: 17.000,
index: 1
},
{
item_name: "Cadillac",
price: 33.500,
index: 2
}
]
});
</script>
Updated code using the method from the answer below. So now, if I pass the products variable, it throws a syntax error at the line gtag("event", "view_item_list". The error by itself says Uncaught SyntaxError: missing ) after argument list
<script>
var products = [];
$(".product").each(function(i) {
products.push({
"name": $(this).find(".name").text(),
"price": $(this).find(".price").text(),
"index": i
})
});
gtag("event", "view_item_list" {
item_list_id: "category_products",
item_list_name: "Products from a category",
items: products
});
</script>
You can use
.eachloop and inside that get the value of name & price using.find()and.text()method . Then , pass the generated array to your gtag items parts .Demo Code :