Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data-target button attribute change via vanilla javascript

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?

like image 651
gileneusz Avatar asked Oct 25 '17 16:10

gileneusz


2 Answers

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>
like image 126
Zakaria Acharki Avatar answered Sep 22 '22 14:09

Zakaria Acharki


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

like image 25
Kumar Shubham Avatar answered Sep 23 '22 14:09

Kumar Shubham