0

I am trying to add a custom data-attr to a script by getting the value after hash from the URL, so when the script is executed at the end of the page it already has the data-segment attr populated.

For example, if the URL is https://domain/#the-hash-tag then the data-segment should be equal to the-hash-tag

var afterHashtag = window.location.hash.substr(1);
//console.log(afterHashtag)

document.getElementById('widget').setAttribute('data-segment', afterHashtag);

<script id="widget" type="text/javascript" src="https://domain/sdk.js" data-segment=""></script>

I am also getting this error

Uncaught TypeError: Cannot read properties of undefined (reading 'setAttribute')

Researching I have found this thread How to change the attributes of the <script> tag, but can't find what can I do in my case.

SOLUTION

Thanks to this thread Why does jQuery or a DOM method such as getElementById not find the element?

Adding a defer to the script and moving .setAttribute after the script did the trick.

<script id="widget" type="text/javascript" src="https://domain/sdk.js" data-segment="" defer></script>

var afterHashtag = window.location.hash.substr(1);
document.getElementById('widget').setAttribute('data-segment', afterHashtag);
lStoilov
  • 1,256
  • 3
  • 14
  • 30
  • The error message is telling you that ```document.getElementById('widget')``` is returning ```undefined```, or in other words, it can't find an element with the id of "widget". Please make sure to run the code after having included the script tag with the id by either running the code beneath the script tag or running it in the body's on load callback. – Alain Doe Jan 30 '22 at 09:03
  • The script is added as it is in the example. You can see that the `id="widget"` is there – lStoilov Jan 30 '22 at 09:05
  • If I move the document.getElementById('widget').setAttribute('data-segment', afterHashtag); after the – lStoilov Jan 30 '22 at 09:24

0 Answers0