Delete/Destroy html table via javascript

Asked

Viewed 168 times

0

When I needed to completely delete a table or any other html element I used jquery $.empty() in the parent element where the element was.

Is there any native way in javascript that does this removal of html elements.

ex: tabela.delete()

In the case of the table it is all generated in the DOM.

2 answers

2


First you need to declare a method to remove the element by its ID:

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}

And then, assuming your table has the ID minha-tabela, you can remove it with:

document.getElementById("minha-tabela").remove();

Or else select her by some class:

document.getElementsByClassName("table-sm").remove();

As an alternative to all of the above, you can also reset the HTML of the element:

document.getElementById("minha-tabela").outerHTML = "";

Source of this question.

1

The method .empty() jQuery removes all elements from within of a single element (Child nodes), but keeps the element itself in the GIFT.

A similar way in pure Javascript, would be to empty the property .innerHTML:

elemento.innerHTML = '';

On the other hand, if you want to remove the element itself (not just yours filhos), which has nothing to do with the .empty() jQuery but with the .remove(), in pure JS would empty the property .outerHTML:

elemento.outerHTML = '';

Or use the API .remove(), not supported in Internet Explorer:

elemento.remove();

But there is a polyfill compatible with IE9+.

Browser other questions tagged

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