0

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
1
  • 1
    Why 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? Commented May 12, 2022 at 7:28

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.