テーブルの要素th
内にタグを挿入したい。実際に挿入している、の下に作成された行オブジェクトのメソッドを使用しています。JS ライブラリを使用しない JavaScript ソリューションはありますか?tr
thead
insertCell
table.tHead
td
更新現在、 Minko Gechevとgaurav
が提供するソリューションと同じものを使用しています。を使用するようなクリーンなソリューションがあるかどうか知りたいinsertCell
ですか?
テーブルの要素th
内にタグを挿入したい。実際に挿入している、の下に作成された行オブジェクトのメソッドを使用しています。JS ライブラリを使用しない JavaScript ソリューションはありますか?tr
thead
insertCell
table.tHead
td
更新現在、 Minko Gechevとgaurav
が提供するソリューションと同じものを使用しています。を使用するようなクリーンなソリューションがあるかどうか知りたいinsertCell
ですか?
最初に要求されたように、insertCell メソッドを使用することもできます。<td>
insertCell メソッドによって作成されたものを上書きするように、outerHTML を変更するだけです。
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
あなたはバニラ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);
table.tHead.children[0].appendChild(document.createElement("th"))
代わりにメソッドを使用してください。基本的にth
、実行時にを作成し、それをtheadに挿入する必要があります。
プロトタイプを変更することで、この機能をネイティブの 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」タグ) は、親が thead タグであるかどうかを確認します。その場合、insertCell と同じ機能を実行しますが、代わりに th タグを使用します。そうでない場合は、元の 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