Skip to content
Advertisement

Dynamically change attribute of html button with Javascript

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() property

       const snipcart = document.querySelector('.snipcart-add-item')
       mydiv.setAttribute("data-item-price", 18)
    
  • Using JavaScript’s dataset property

       const snipcart = document.querySelector('.snipcart-add-item')
       snipcart.dataset['item-price'] = 18
       //or use camelCase turn into kabeb-case
       snipcart.itemPrice = 18
    
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement