5

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);
    }
}
4
  • Can you show us what you've tried? so that we can help you better Commented May 10, 2018 at 9:30
  • Need an identifier for the div. Commented May 10, 2018 at 9:34
  • "Table" is the identifier of div Commented May 10, 2018 at 9:40
  • This is exactly the same question stackoverflow.com/questions/3955229/… Commented May 10, 2018 at 9:54

3 Answers 3

13

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

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

2 Comments

This approach does not remove the event handlers of the removed child nodes, potentially leading to memory leak.
@danefondo could you kindly expand? I understand the first part of your comment but I don't know enough to understand how that could create a memory leak thank you.
3

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

2 Comments

You have an extra closing paren. Should be box.removeChild(box.lastChild);
hasChildElements? Maybe you mean "hasChildNodes" (developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes)
1

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.

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

Comments

Your Answer

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