Chnage script attr with js – reading ‘setAttribute’ error

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.