javascripthtml-tabletableheader

Get cellIndex of TableHeader with javascript


Situation: I have created a html table header entirely with javascript and now I want to add a delete column feature which takes the cell index as an argument. However, every time I try to get the cell index of the created th element the index obtained is -1. Once I get the element by tag name there is no longer any issues with getting the respective cell indices of the header.

Any help is highly appreciated.

let headerFragment = document.createDocumentFragment();

//Append counter at the beginning of each row
let number_th = document.createElement("th")
let number_txt = document.createTextNode('#');
number_th.appendChild(number_txt);
headerFragment.appendChild(number_th);
//Append active checkbox
let active_th = document.createElement("th")
let active_txt = document.createTextNode('Active');
active_th.appendChild(active_txt);
headerFragment.appendChild(active_th);

//Append all other data fields
if (headersArray){
    headersArray.forEach((header, index) => {

        let th = document.createElement("th");

        //Create text identifier
        let txt = document.createTextNode(headersArray[index]);
        //Create delete column button
        let delete_column = document.createElement("p");
        delete_column.innerHTML = "Delete";

        delete_column.onclick = function() {
            //Delete column - here is the problem 
            alert(th.cellIndex) //alerts -1
            deleteColumn(th.cellIndex);
        }

        th.appendChild(txt);
        th.appendChild(delete_column);
        headerFragment.appendChild(th);

    });

    //Final append
    tableHeader.appendChild(headerFragment);
}

If I run this function all indices are properly retrieved

function myFunction() {
var x = document.getElementsByTagName("th");
var txt = "";
var i;
for (i = 0; i < x.length; i++) {
    txt = txt + "The index of Cell "+(i+1)+" is: "+x[i].cellIndex+"<br>";
}

alert(txt);

}


Solution

  • The docs state that cellIndex returns -1 when the cell doesn't belong to a tr, so my guess would be that that is the case.