Вставить th в thead
Я хочу вставить тег th
внутри tr
элемента thead
таблицы. Я использую метод insertCell
объекта строки, созданный в table.tHead
, который фактически вставляет td
. Есть ли какое-либо решение JavaScript без использования какой-либо JS-библиотеки?
Обновление
В настоящее время я использую что-то такое же, что и решение Минько Гечева и gaurav. Я хочу знать, есть ли какое-нибудь чистое решение, например, используя insertCell
?
Ответы
Ответ 1
Вы можете сделать это с помощью ванильного JavaScript. Попробуйте следующее:
HTML
<table id="table">
<thead>
<tr>
<th>First</th>
</tr>
<thead>
</table>
JavaScript
var tr = document.getElementById('table').tHead.children[0],
th = document.createElement('th');
th.innerHTML = "Second";
tr.appendChild(th);
Вот пример http://codepen.io/anon/pen/Bgwuf
Ответ 2
Вы также можете использовать метод insertCell, как первоначально запрошено. Вам просто нужно изменить outerHTML, чтобы перезаписать <td>
, созданный методом insertCell:
var table = document.createElement("TABLE")
var row = table.insertRow(0);
row.insertCell(0).outerHTML = "<th>First</th>"; // rather than innerHTML
В соответствии с приведенным примером:
HTML
<table id="table">
<thead>
<tr>
<th>First</th>
</tr>
<thead>
</table>
Javascript
var tr = document.getElementById('table').tHead.children[0];
tr.insertCell(1).outerHTML = "<th>Second</th>" // some browsers require the index parm -- 1
Ответ 3
Используйте вместо этого метод table.tHead.children[0].appendChild(document.createElement("th"))
. В основном вам нужно создать th
во время выполнения и вставить его в ваш thead.
Ответ 4
Вы можете добавить эту функциональность в собственный HTMLTableRowElement, изменив ее прототип:
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);
После запуска этого кода любые новые теги HTMLTableRowElements (теги "td" ) проведут проверку, является ли родительский тег тегом. Если это так, он будет выполнять те же функции, что и insertCell, но вместо этого использует т-й тег. Если нет, он просто будет использовать оригинальную функциональность insertCell.
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
Обратите внимание, что обычно не рекомендуется распространять собственные объекты.