Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

380
Views
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.

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);
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!