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

383
Views
Cambie el script attr con js - leyendo el error 'setAttribute'

Estoy tratando de agregar un atributo de datos personalizado a una secuencia de comandos obteniendo el valor después del hash de la URL, de modo que cuando la secuencia de comandos se ejecuta al final de la página, ya tiene el atributo data-segment poblado.

Por ejemplo, si la URL es https://domain/#the-hash-tag, entonces el data-segment debe ser igual a 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>

yo tambien estoy recibiendo este error

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

Investigando he encontrado este hilo Cómo cambiar los atributos de la etiqueta <script> , pero no encuentro que puedo hacer en mi caso.

SOLUCIÓN

Gracias a este hilo ¿Por qué jQuery o un método DOM como getElementById no encuentra el elemento?

Agregar un defer a la secuencia de comandos y mover .setAttribute después de que la secuencia de comandos hizo el truco.

 <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!