Как создать таблицу внутри другой таблицы, используя JavaScript? - PullRequest
0 голосов
/ 14 мая 2019

Я использую JavaScript для динамического создания таблицы.У меня есть минимальный пример того, что я хочу.Вот HTML-код для генерации:

    <table id='mainTable'>
       <tr> 
          <td> Row 1 Cell 1 </td> 
       </tr>
       <tr> 
          <td> 
             <table>
                <tr> 
                   <td> ... </td>
                </tr>
             </table>
          </td> 
       </tr>
    </table>

Я получаю основную таблицу через var table1 = document.getElementById("mainTable");, а затем добавляю строки и ячейки, используя JavaScripts insertRow(0) и insertCell(0).Я просто хочу знать, как добавить новую таблицу в ячейку TD.

1 Ответ

1 голос
/ 14 мая 2019
// create new table
const newTable = document.createElement('table')

// target cell, this is selecting every td inside your mainTable
const target = document.querySelectorAll('#mainTable td')

// add new Table to first cell (if you want to add to specific cell you can add a class to it and the target it like that) or change the number in brackets:
target[0].appendChild(newTable)
...