Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

382
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda