Możesz dodać tę funkcjonalność do natywnego HTMLTableRowElement zmieniając To prototyp:
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);
Po uruchomieniu tego kodu, wszelkie nowe HTMLTableRowElements („TD” tagi) sprawdza, czy rodzic jest tag thead. Jeśli tak, to wykona tę samą funkcjonalność co insertCell, ale zamiast tego użyje tagu th. Jeśli nie, po prostu użyje oryginalnej funkcji insertCell.
Zauważ, że it is generally not recommended to extend the native objects.
Należy pamiętać, 'th' jak natychmiastowe dziecko' thead' jest nieważny i może doprowadzić do niechcianych konsekwencji w różnych przeglądarkach. Poprawny układ wygląda tak: 'table-> thead-> tr-> th' –
Przepraszam, Mój zły, miałem na myśli' th' wewnątrz tr of thead. –
Naprawiłem odpowiedź z 'tr' wewnątrz' thead' :-) –