Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading