TransWikia.com

Get cellIndex of TableHeader with javascript

Stack Overflow Asked on December 25, 2021

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

}

2 Answers

I suggest you assign an id dynamically to your "th" element and then delete it using that id.

declare a variable

let i = 0; and then

let th = document.createElement("th");
th.id = i++;

in your delete may be

        delete_column.onclick = function() {
            let elementToDelete = document.getElementById(th.id);
            elementToDelete.parentNode.removeChild(elementToDelete);
        }

Answered by Declare on December 25, 2021

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.

Answered by Bart Barnard on December 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP