data-target button attribute change via vanilla javascript

18,639

Solution 1

The right way to manage data-* attributes is by using dataset :

var backOfferButton = document.getElementById('back_offer_button');
backOfferButton.dataset.target = "#addDifferentOffer";

Hope this helps.

var backOfferButton = document.getElementById('back_offer_button');

console.log(backOfferButton.dataset.target);

backOfferButton.dataset.target = "#addDifferentOffer";

console.log(backOfferButton.dataset.target);
<button id="back_offer_button" type="button" class="btn btn-default" data-dismiss="modal" data-toggle="modal" data-target="#addOffer">Go back</button>

Solution 2

Yes, as stated in the comment also, the general way of setting/getting HTML attribute values is by using the setAttribute(),getAttribute() methods.

So , you would do something like:

let element = document.getElementById('#someId'); element.setAttribute('name-of-the-attribute', value); Have a look here

Share:
18,639
gileneusz
Author by

gileneusz

I'm not a professional coder, I'm doing my own projects from scratch, without any knowledge. That's maybe why I sometimes ask stupid questions :) I've learned Laravel, Vue js, and some web technologies.

Updated on June 05, 2022

Comments

  • gileneusz
    gileneusz about 2 years

    Ive got button that is closing bootstrap modal as below:

    <button id="back_offer_button" type="button" class="btn btn-default" data-dismiss="modal" data-toggle="modal" data-target="#addOffer">Go back</button>
    

    I want to be able to dynamic change data-target via vanilla javascript to different location:

    For example now is

    data-target="#addOffer"
    

    I want to change it to

    data-target="#addDifferentOffer"
    

    So I tried to get this button:

    var backOfferButton = document.getElementById('back_offer_button');
    

    And then:

    backOfferButton.data-target = "#addDifferentOffer" <?>
    

    This of course doesn't work. How should it be written correctly?

  • gileneusz
    gileneusz over 6 years
    This is also the right way, thank you again for your help
  • GramThanos
    GramThanos over 6 years
    Heads up for compatibility with old browsers (if you target them), developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
  • gileneusz
    gileneusz over 6 years
    @ZakariaAcharki Thank you for your suggestion, I've changed the accepted answer. I'm beginner so I cannot make this kind of decisions correctly yet
  • Zakaria Acharki
    Zakaria Acharki over 6 years
    Welcome to stackOverflow world, glad I could helps.