onClick event doesn't work inside form tag
The form is getting submitted and your page is reloaded. You need to stop the form submit.
Solution 1: Add a type
attribute to your button.
<button type="button" onclick="removeP2();">Remove</button>
This will make sure that the button is not of submit
type (which is the default type for buttons inside form tag when type is not specified), and that the form is not submitted on click.
Solution 2: Prevent the Submit event in javascript. So make these changes.
<button onclick="removeP2(event);">Remove</button>
and in the script prevent this event
function removeP2(event) {
event.preventDefault(); // prevent the event , ie form submit event
var parent = document.getElementById("section");
var child = document.getElementById("p2");
parent.removeChild(child);
}
Solution 3: I dont see any need of the form tag over there in the HTML. If its the exact syntax of yours and you really dont have any other elements or purpose with the form submission then you can remove the form
tag.
<nav>
<button onclick="removeP2();">Remove</button>
</nav>
Use the code below. It won't submit the form.
<button type="button">My Button</button>