I have an html button where the ‘data-item-price’ attribute needs to be dynamically set on page load. The button has to be html but I can manipulate it with Javascript.
<button class="snipcart-add-item" data-item-id="Job123" data-item-price= 18 *a dynamically passed number* data-item-url= "www.abc.co/priceevaluation" data-item-name="Validate"> Add to cart </button>
Advertisement
Answer
Using DOM’s
setAttribute()
propertyconst snipcart = document.querySelector('.snipcart-add-item') mydiv.setAttribute("data-item-price", 18)
Using JavaScript’s
dataset
propertyconst snipcart = document.querySelector('.snipcart-add-item') snipcart.dataset['item-price'] = 18 //or use camelCase turn into kabeb-case snipcart.itemPrice = 18