How to remove all elements from a javascript div?

Asked

Viewed 1,775 times

1

How to remove all elements of a div at once removeChild() removes only one element?

  • How did you try to do it? You came to write some code?

2 answers

4

To remove the descendants of an element at once set the value of the property innerText of this element as an empty string.

The estate innerText returns the text content of the "as rendered" element and when defined replaces the children of the element with the value provided.

Example:

function limpar() {
  let alvo = document.getElementById("alvo");
  
  // Remove todos os descendentes da <div id="alvo">
  alvo.innerText = "";

  console.log(alvo); // Exibe o texto atual da <div>
}
<button onclick="limpar()">Limpar div</button>

<div id="alvo">
  <ul>
    <li>Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.</li>
    <li>Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.</li>
    <li>Phasellus ultrices nulla quis nibh. Quisque a lectus. Donec consectetuer ligula vulputate sem tristique cursus. Nam nulla quam, gravida non, commodo a, sodales sit amet, nisi.</li>
    <li>Pellentesque fermentum dolor. Aliquam quam lectus, facilisis auctor, ultrices ut, elementum vulputate, nunc.</li>
  </ul>
  <svg height="210" width="500">
  <polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:nonzero;"/>      
</svg>
</div>

1

To remove all elements, you must go through the child elements through a loop for, removing them with the method remove(). See the example below:

function removeAll(){
    const div = document.getElementById("<sua_div>");
    
    for (child of div.children){
        child.remove();
    }
}

Another simple way to erase all the child elements of the div, is using the method empty() jquery. See below:

const div = $("<sua_div>");
div.empty(); // Apagar todos os elementos dentro da div
  • If you want you can take the elements with querySelectorAll("div *") using the selector *

Browser other questions tagged

You are not signed in. Login or sign up in order to post.