I'm using vanilla javascript to parse HTML data attributes and after that, I need to parse to a different list in a different format. how can I parse them as array list with all products
HTML
<div>
<img src="img1.jpg" />
<div class="description">Lagavulin 16 Year Old</div>
<button class="add-to-cart" data-product-id="1" data-product-title="Lagavulin 16 Year Old" data-category="Scotch">
Add To Cart
</button>
</div>
<div>
<img src="img2.jpg" />
<div class="description">Ardbeg</div>
<button class="add-to-cart" data-product-id="10" data-product-title="Ardbeg" data-category="Scotch">
Add To Cart
</button>
</div>
</div>
JS:
Array.from(
document.getElementById("main-menu")
.getElementsByTagName("li")
).forEach((x) =>
(x.onclick = () =>
console.log({
event_name: "menu item clicked",
menu_item: x.innerText,
}))
);
Im expecting to create an array with all the products that would look like this
"name": <str>, mandatory
"id": <int>, mandatory
"price": <float>, mandatory
"brand": <str>, optional
"list": <str>, optional
"position": <int>, optional
RenaudC5
3,8591 gold badge13 silver badges32 bronze badges
-
1Why are you setting .onclick? Do you know how to get from the <li> to the child elements you need? And how to read their data?user5734311– user57343112022年05月12日 07:28:05 +00:00Commented May 12, 2022 at 7:28
1 Answer 1
You can extract the information from the HTML as the below code shows, but I don't understand from where you are expecting to get brand & position since you there's no such information in the HTML.
var itemsElems = document.querySelectorAll('.add-to-cart');
var result = [...itemsElems].reduce((acc, elm) => {
var {productId: id, productTitle: name, category} = elm.dataset || {};
acc.push({
id: +id, // cast to number
name,
category,
})
return acc
}, []);
console.log(result)
<div>
<img src="img1.jpg" />
<div class="description">Lagavulin 16 Year Old</div>
<button class="add-to-cart" data-product-id="1" data-product-title="Lagavulin 16 Year Old" data-category="Scotch">
Add To Cart
</button>
</div>
<div>
<img src="img2.jpg" />
<div class="description">Ardbeg</div>
<button class="add-to-cart" data-product-id="10" data-product-title="Ardbeg" data-category="Scotch">
Add To Cart
</button>
</div>
answered May 12, 2022 at 7:53
vsync
133k61 gold badges345 silver badges430 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js