最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

data-target button attribute change via vanilla javascript - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Oct 25, 2017 at 16:39 Zakaria Acharki 67.5k15 gold badges78 silver badges105 bronze badges asked Oct 25, 2017 at 16:17 gileneuszgileneusz 1,4859 gold badges35 silver badges55 bronze badges 1
  • 3 backOfferButton.setAttribute('data-target', '#addDifferentOffer')? – CRice Commented Oct 25, 2017 at 16:18
Add a comment  | 

2 Answers 2

Reset to default 14

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>

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

发布评论

评论列表(0)

  1. 暂无评论