简体   繁体   中英

How to pass a JavaScript variable to DIV tag?

I am trying a code to pass a javascript variable to the div tag to change its attribute. If anyone knows how to do this, help me.

<div id="rate" class="money" data-wpac-chan=""></div>

I want to pass a javascript variable to the data-wpac-chan.

<script type="text/javascript">    
    var div = document.getElementById("rate").data-wpac-chan = "bal";
</script>

It is not working. I want to replace data-wpac-chan=" " to data-wpac-chan="bal"

This should do it:

document.getElementById("rate").setAttribute("data-wpac-chan", "bal");

SetAtrribute will set any attribute on an HTML element.

You can also use dataset to assign the value to the attributes that has data- . Notice that, you need to use the camelcase as attribute name. So, wpac-chan becomes wpacChan

 document.getElementById("rate").dataset.wpacChan = 'bal'
 <div id="rate" class="money" data-wpac-chan="">sadasd</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM