0

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 :)

1
  • 1
    Use document.getElementById('form').innerHTML = ''; instead. The innerHTML attribute get and set the inner html of the element as a string. Commented Nov 14, 2021 at 12:29

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.