2016-08-31 4 views
0

テーブルに新しい行を追加するときに問題が発生しました。 問題は、新しい行がブロックではなくblcokに追加されることです。任意の助けHTML dom insertRow()

function myFunction() { 
 
    var table = document.getElementById("myTable"); 
 
    var row = table.insertRow(1); 
 
    var cell1 = row.insertCell(0); 
 
    var cell2 = row.insertCell(1); 
 
    cell1.innerHTML = "NEW CELL1"; 
 
    cell2.innerHTML = "NEW CELL2"; 
 
}
table{ 
 
    border: 1px solid #ccc; 
 
}
<table id="myTable"> 
 
    <thead> 
 
     <tr> 
 
     <th>Product</th> 
 
     <th>Description</th> 
 
     </tr> 
 
    </thead> 
 

 
    <tbody> 
 
     //new row is supposed to add into here. 
 
    <tbody> 
 
</table> 
 
<br> 
 

 
<button onclick="myFunction()">Try it</button>

感謝。

答えて

1

あなたはtbodyに新しい行を追加し、その上getElementsByTagName("tbody")を使用して最初のTBODYを選択したかったです。また、代わりにinsertRow(0)を使うinsertRow(1)

function myFunction() { 
 
    var table = document.getElementById("myTable"); 
 
    var tbody = table.getElementsByTagName('tbody'); 
 
    console.log(tbody) 
 
    var row = tbody[0].insertRow(0); 
 
    var cell1 = row.insertCell(0); 
 
    var cell2 = row.insertCell(1); 
 
    cell1.innerHTML = "NEW CELL1"; 
 
    cell2.innerHTML = "NEW CELL2"; 
 
}
table{ 
 
    border: 1px solid #ccc; 
 
}
<table id="myTable"> 
 
    <thead> 
 
     <tr> 
 
     <th>Product</th> 
 
     <th>Description</th> 
 
     </tr> 
 
    </thead> 
 

 
    <tbody> 
 
     //new row is supposed to add into here. 
 
    <tbody> 
 
</table> 
 
<br> 
 

 
<button onclick="myFunction()">Try it</button>