Home > Blockchain >  Dynamically change attribute of html button with Javascript
Dynamically change attribute of html button with Javascript

Time:07-11

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 
  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>

CodePudding user response:

  • 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
    
  • Related