Question

How can I delete all the tables in a web page? The tables don't have any ids associated with them.

Was it helpful?

Solution

Very simple version:

var tables = document.getElementsByTagName("TABLE");
for (var i=tables.length-1; i>=0;i-=1)
   if (tables[i]) tables[i].parentNode.removeChild(tables[i]);

OTHER TIPS

Danger! getElementsByTagName returns a ‘live’ NodeList. In Joel's code, removing element 0 moves the items in the list down so that when you remove element 1, you've missed one.

Possible alternatives: if you know you're always going to be removing every element, you can use a while-loop:

var tables= document.getElementsByTagName('table');
while (tables.length>0)
    tables[0].parentNode.removeChild(tables[0]);

Or, if you might or might not remove, but iteration order is unimportant, go through the list backwards:

var tables= document.getElementsByTagName('table');
for (var i= tables.length; i-->0;)
    tables[i].parentNode.removeChild(tables[i]);

If you might-or-might-not remove and you need to iterate forwards, you're in the tedious position of having to copy the list:

function toArray(l) {
    var a= [];
    for (var i= 0; i<l.length; i++)
        a[i]= l[i];
    return a;
}

var tables= toArray(document.getElementsByTagName('table'));
for (var i= 0; i<tables.length; i++)
    ...

If you're using jQuery it is pretty easy ...

$(document).ready(function() {
  $("table").remove();
});

not sure how's you do it in other libraries.

if you're not using a js library, you should be.

Or:

function myF() {
    this.checkChild = function(tagN, node) {
        if (node.tagName.toLower() == tagN.toLower()) {
            node.parentNode.removeChild(node);
        }
        else {
            var i;
            for(i = 0; i < node.childNodes.length; i++)
                this.checkChild(tagN, node.childNodes[i]);
        }
    }
}

Usage:


var m = new myF();
m.checkChild("The name of the tagname. This case: table", document.body); 
 

Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top