2013-02-21 4 views
20

thタグをtrtheadの表の中に挿入したいと思います。私はtable.tHeadの下に作成された行オブジェクトのinsertCellメソッドを使用していますが、実際にはtdが挿入されています。 JSライブラリを使用しないJavaScriptソリューションはありますか?thethadに挿入する

更新 は現在、私はMinko Gechevgauravが提供するソリューションと同じものを使用しています。 insertCellのようなきれいな解決策があるかどうかを知りたいですか?

+1

は無効であり、さまざまなブラウザでは、不要な結果をもたらす可能性がthead' 'th'として直接の子'、助言されることに注意してください。有効なレイアウトは次のようなものです: 'table-> thead-> tr-> th' –

+0

申し訳ありません、私の悪い、私はthの中のthを意味しました。 –

+0

私は 'thead'の中で' tr'を使って自分の答えを修正しました:-) –

答えて

10

バニラの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

7

代わりにtable.tHead.children[0].appendChild(document.createElement("th"))メソッドを使用してください。基本的には実行時にthを作成し、それをあなたのテッドに挿入する必要があります。

16

最初に要求されてます。また、insertCellメソッドを使用することができます。

Javascriptを

HTML

<table id="table"> 
    <thead> 
    <tr> 
     <th>First</th> 
    </tr> 
    <thead> 
</table> 

var table = document.createElement("TABLE") 
var row = table.insertRow(0); 
    row.insertCell(0).outerHTML = "<th>First</th>"; // rather than innerHTML 

与えられた例を一致させるために:あなたはinsertCellメソッドによって作成<td>を上書きするouterHTMLを変更する必要があります

var tr = document.getElementById('table').tHead.children[0]; 
    tr.insertCell(1).outerHTML = "<th>Second</th>" // some browsers require the index parm -- 1 
+0

ChromeとFirefoxでうまく動作しますが、outerHtmlがIE 6で動作しない –

+0

ヘッダー行( 'tr')に新しいヘッダーセル(' th')の位置がどのように影響するかは、これが唯一の方法ですか? – kabeleced

0

あなたはそれのプロトタイプを変更することにより、ネイティブ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機能を使用します。

it is generally not recommended to extend the native objects.

関連する問題