Shree Ritz Shree Ritz - 1 year ago 125
HTML Question

document.body.appendChild() not working with <form>

I am running the code from w3schools to add button dynamically to the page. Here is the code.



<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.appendChild(t);
document.body.appendChild(btn);
}
</script>
</body>
</html>





But this dynamic addition doesn't work when I have a
<form>
tag. What changes in the JavaScript I can make to accommodate dynamic button without having to remove the
<form>
tag?

Answer Source

function myFunction() {
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode("CLICK ME");
    btn.appendChild(t);
    document.getElementById('theForm').appendChild(btn);
}
</script>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Try it</button>
<form id="theForm">
</form>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download