Skip to content
Advertisement

javascript why i cannot appendchild to html div using javascript function

i need to append a child control to html element using javascript, the problem is that the child is appear when call the function and disappear directely the child must be in a form tag

this is the code when i append child to the html elemet

<html>
 <body>
  <form  >
<button onclick="create()">Create Heading</button>

</form>

    <script>
  function create() {
    var h1 = document.createElement('h1');
    h1.textContent = "New Heading!!!";
    h1.setAttribute('class', 'note');
    document.body.appendChild(h1);
  }
</script>
   </body>
   </html>

the element h1 is added to the layout appear and disappear immediately but when i remove the <form> it works perfectly

Advertisement

Answer

It looks like the form element is submitting when you press the button, refreshing the page and making the header disappear. You should probably ask yourself: should I really need a form? Are there some inputs that should be handled by the server?

If you really need it, then you can try to prevent the form from submitting

Also, as pointed out in this SO Question you can prevent the button to submit the form by specifying its type as ‘button’.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement