简体   繁体   中英

How to delete all Child Elements from a div element using JS

Hey guys i am learning JS, the thing is i made a simple application which display the multiplication table of the input number. The problem is that when i enter a number again the it will print below the previous multiplication table so i want to delete all the child element of div tag when i enter a number again

function print() {
    var box = document.getElementById("table");

    for(let i=1 ; i<=10 ; i++) {
        var t = document.getElementById("tabInput").value;
        var t_Element = document.createElement("p");
        var t_line = document.createTextNode(t + " x " + i + " = " + t*i);
        t_Element.appendChild(t_line);
        box.appendChild(t_Element);
    }
}

If you need to clear ALL elements, then there is no need to iterate through them.

You can just clear the innerHTML of the div like so:

document.getElementById('yourdivid').innerHTML = '';

And then you can proceed with the rest of your code that creates the new elements

If you clear the html with innerHTML = '' , you still are going to have those previous html nodes loaded. For now the best way to do it is to iterate and destroy each node with

while (box.hasChildElements()) {
  box.removeChild(box.lastChild))
}

if you have a lot of elements and need a really fast way, you can clone the node with false deep option then replace it.

let parentNode = document.querySelector("#parentNode"),
   replacedNode = document.querySelector("#replacedNode"),
   newNode = replacedNode.cloneNode(false);
parentNode.replaceChild(newNode, replacedNode)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM