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

175
Vistas
Why does .setAttribute not work when nested inside a function?

I'll make it quick. I researched a lot but I'm not sure why this is not working.

I have a textarea tag which I want to set to 'data-something' tag using setAttribute("data-something","") command and it works just fine if I just list it out there. However what I'm doing is I"m creating a button that when clicked sets the attribute of the textarea to 'data-something', and no matter what it fails to operate when I nest setAttribute inside a myFunction and set button onclick="myFunction()". I'd appreciate if someone could explain a workaround that.

Thanks a ton for your patience.

This is what works:

<textarea></textarea>

<script>
textarea.setAttribute("data-something","")
</script>

This is what doesn't work

<textarea></textarea>

<button onclick="myFunction()"></button>

<script>
function myFunction(){
textarea.setAttribute("data-something","")
}
</script>
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

You have to give you element a handle getElementById then make the change

function myFunction(){
  let textarea = document.getElementById("Foo");
  textarea.setAttribute("data-something","This is the set Data");
  console.log(textarea);
}
<textarea id="Foo"></textarea>

<button onclick="myFunction()">Click me</button>

about 4 years ago · Santiago Gelvez Denunciar
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