简体   繁体   中英

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

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

Agreeing with @Drago96 Form submits and page refreshes.

What is the point of the form . if you are only appending an element

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

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM