Javascript set attribute in script tag with variable

Asked

Viewed 99 times

-2

How to pass a variable to the script attribute, 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 cannot pass the value of the token variable, what happens is that data-token takes the variable name as if it were string, and not its value.

1 answer

0

It follows a way of doing it, although I don’t know if it’s the ideal way or if it meets what you want to do with it in particular:

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.