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

191
Views
error while changing element in DOM using vannilla JS

I have create a program to change an element in a HTML while a button is clicked, but it causes an error

<button id='change'>hi</button>

<p id="pp">text</p>

<script>
    var myfunction=function(e){
        e.preventDefault();
        document.getElementById('pp').innerHTML=<p id="pp">change</p>
    }
    document.getElementById('change').addEventListener('click',myfunction(e))
</script>

codesand box link

https://codesandbox.io/s/bold-waterfall-90e74

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

you have 2 problems. one is you're passing the return value of myFunction into .addEventListener with the value of e which is not defined. the other is your not setting the .innerHTML correctly. I'm not sure if you can create HTML elements in JavaScript using HTML syntax, but if you can, you're creating another <p> element with the same id. Also, .innerHTML should be a String and all HTML attributes should have double quotes. try this:

document.getElementById('change').addEventListener('click', function (e) {
  e.preventDefault();
  document.getElementById('pp').innerHTML = "change";
})
<button id="change">hi</button>

<p id="pp">text</p>

You also probably shouldn't create functions with var functionName = function() {...} because it can cause hoisting problems. var is also deprecated and can cause bugs so I would advise to use const and let.

about 4 years ago · Juan Pablo Isaza Report

0

fix this string:

document.getElementById('change').addEventListener('click', myfunction)
about 4 years ago · Juan Pablo Isaza Report

0

You were missing quotes around the innerHTML value.

When calling addEventListener, your EventListener is the function "myfunction". You don't have to call it.

<button id='change'>hi</button>

<p id="pp">text</p>

<script>
    var myfunction=function(e){
        e.preventDefault();
        document.getElementById('pp').innerHTML='<p id="pp">change</p>'
    }
    document.getElementById('change').addEventListener('click',myfunction)
</script>

about 4 years ago · Juan Pablo Isaza 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!