Javascript – Dynamically delete multiple columns in html table


I am trying to delete multiple columns from html table using javascript.
The logic it is using is that it searches in top row for tag "" and then deletes that column.

The problem is if only one cell in top row is having '', then it deletes that columns fine, but if there are multiple columns it throws error.

Here is my code

<!DOCTYPE html>
<table style="width:100%" border='1' id='Just_for_california'>



    var dataTable_length = document.getElementById('Just_for_california').rows[0].cells.length;
    var count_rows = document.getElementById('Just_for_california').rows.length;
    var column_array = [];
    for(var i=0; i<dataTable_length; i++)
        var str = document.getElementById("Just_for_california").rows[0].cells[i].innerHTML;
        if("<span></span>") != -1)

    var len = column_array.length;
    for(var i=count_rows-1 ; i>=0;i--)
        rows_number = document.getElementById('Just_for_california').rows[i];

            for(var j=0; j<len;j++)



Best Solution

It happens because you calculate indexes incorrectly when you delete cells. I refactored you code (making it clearer) and it seems to work now:

var table = document.getElementById('Just_for_california'),
    rows = table.rows;

for (var i = 0; i < rows[0].cells.length; i++) {
    var str = rows[0].cells[i].innerHTML;
    if ("<span></span>") != -1) {
        for (var j = 0; j < rows.length; j++) {

The problem is that you are trying to remove cells "horizontally" in the row. So say you want to delete cells at indexes 1 and 3 and there are 4 columns in the table. When you delete the first cell 1 it works fine. However then you move to the right and try to remove cell at index 3. This fails because since you have already removed cell 1, there is no cell with index 3 anymore. The maximum index now is 2. Hence the error.

In my improved code I'm removing columns "vertically", so such an issue can't happen.