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
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.
fix this string:
document.getElementById('change').addEventListener('click', myfunction)
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>