Javascript set attribute in script tag with variable

-2

How to pass a variable to the attribute of a script, example:

<script>
     token = "ablsicn05101dad10561" //exemplo. Esse token eu pego pela URL
</script>

<script 
  type="text/javascript"
  src="http://.."
  data-token=token>
</script>

The problem is that I can not pass the value of the variable token, what happens is that the data-token receives the name of the variable as if it were string, not the value of it.

    
asked by anonymous 06.11.2018 / 13:32

1 answer

0

Here's a way to do it, although I do not know if it's the ideal way or what you want to do with it specifically:

<script>
  token = "ablsicn05101dad10561"
</script>

<script type="text/javascript" src="http://.."> 
  document.currentScript.setAttribute('data-token', token)
</script>

Using the currentScript property, you can refer to the script tag where the code is, simply and easily. Then you use setAttribute to set the value you want inside the tag.

    
06.11.2018 / 14:23