Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

fix this string:

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda