1

Can I forward a variable from script tag to a current script? Something like this:

<script type="text/template" id="myscript" myvar="123123">

    var filename = document.getElementById("myscript").myvar;

</script>
Norgul
  • 4,613
  • 13
  • 61
  • 144
  • In the code you posted, it looks like you're referencing the *same* script tag? Not sure what you're trying to do, but you can access the attribute with `getAttribute` (but better to use data- attributes for custom attributes) – CertainPerformance Oct 21 '18 at 08:16
  • I would like to access that variable in the same script yes. How can I reference the current script I'm in? (not really a FE dev) – Norgul Oct 21 '18 at 08:18
  • Can you explain what you are trying to achieve? – Daniel Hilgarth Oct 21 '18 at 08:27
  • You need to change the type of your script tag. It won't work if the type of your script is not JavaScript (by default it is but in your example you put `type="text/template"`). Then you can use `getAttribute`. It will return the attribute value of your element : `document.getElementById('myscript').getAttribute('myvar')` – ElJackiste Oct 21 '18 at 08:29

1 Answers1

4

You can use document.currentScript to reference the currently running <script> tag:

<script type="text/javascript" id="myscript" myvar="123123">
console.log(
  document.currentScript.getAttribute('myvar')
);
</script>

Another option is to select the script tag like you would select any element, with querySelector, and then get the attribute:

<script type="text/javascript" id="myscript" myvar="123123">
console.log(
  document.querySelector('#myscript').getAttribute('myvar')
);
</script>

But when using custom attributes, it would probably be more appropriate to use a data- attribute:

<script type="text/javascript" id="myscript" data-myvar="123123">
console.log(
  document.currentScript.dataset.myvar
);
</script>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320