Insert th in thead

后端 未结 4 1888
时光取名叫无心
时光取名叫无心 2021-02-01 16:15

I want to insert a th tag inside tr of thead element of a table. I am using insertCell method of row object created under

4条回答
  •  逝去的感伤
    2021-02-01 16:37

    You can add this functionality to the native HTMLTableRowElement by changing it's prototype:

    HTMLTableRowElement.prototype.insertCell = (function(oldInsertCell) {
        return function(index) {
            if (this.parentElement.tagName.toUpperCase() == "THEAD") {
                if (index < -1 || index > this.cells.length) {
                    // This case is suppose to throw a DOMException, but we can't construct one
                    // Just let the real function do it.
                } else {
                    let th = document.createElement("TH");
                    if (arguments.length == 0 || index == -1 || index == this.cells.length) {
                        return this.appendChild(th);
                    } else {
                        return this.insertBefore(th, this.children[index]);
                    }
                }
            }
            return oldInsertCell.apply(this, arguments);
        }
    })(HTMLTableRowElement.prototype.insertCell);
    

    After this code is run, any new HTMLTableRowElements ("td" tags) will check to see if the parent is a thead tag. If so, it will do the same functionality as insertCell, but using a th tag instead. If not, it will just use the original insertCell functionality.

    document.querySelector("thead > tr").insertCell(); // inserts a th into a tr inside a thead
    document.querySelector(":not(thead) > tr").insertCell(); // inserts a td into a tr not inside a thead
    

    Note that it is generally not recommended to extend the native objects.

提交回复
热议问题