2016-08-31 2 views
0

Я столкнулся с проблемой во время tring, чтобы добавить новую строку в таблицу. Проблема заключается в том, что новая строка добавляется в 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, поэтому сначала выберите tbody, используя getElementsByTagName("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>