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

173
Views
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 answers
Answer question

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