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

193
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

fix this string:

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

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