I am doing a class exercise.
I have to create an onclick function that remove the elements
that are inside the form
<div id="content">
<form id="form">
<p>Hola</p>
<p>que</p>
<p>tal</p>
</form>
</div>
I need to remove the p elements with js.
I was doing something like this, but tbh I do not know how to do it
document.getElementById('form').appendChild("");
Thank you in advance :)
A single child can be removed by calling the native Node.removeChild(child) method on it's parent. Wrapping this method in a while loop enables you to remove every child of a specified parent node:
function removeAllChildren(parent) {
while(parent.firstChild) {
parent.removeChild(parent.firstChild)
}
}
// usage:
const form = document.getElementById('#form');
removeAllChildren(form);
As written in MDN:
If the return value of removeChild() is not stored, and no other reference is kept, it will be automatically deleted from memory after a short time.
This is why this approach is far superior compared to the simpler parent.innerHTML = '' method, which could lead to memory leaks.
Explanation: document.querySelector('.remove-p-tags-button') selects your button and addEventListener attaches a function/event listener to that button whenever it's clicked. Inside the call back for the addEventListener it selects all the p tags within the form and removes them.
document.querySelector('.remove-p-tags-button').addEventListener('click', (e) => {
document.querySelectorAll('#form p').forEach(el => el.remove());
});
<div id="content">
<form id="form">
<p>Hola</p>
<p>que</p>
<p>tal</p>
</form>
<button class="remove-p-tags-button">Remove P tags</button>
</div>
You can use querySelectorAll to fetch and remove to remove selected elements from DOM.
function removePTags() {
document.querySelectorAll("#form p").forEach(e => e.remove());
}
<div id="content">
<form id="form">
<p>Hola</p>
<p>que</p>
<p>tal</p>
</form>
<button onclick="removePTags()">Remove p</button>
</div>