“This is the 28th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

The operating Table

In the era of front and back end development, back-end engineers were most used to using Table to develop forms and list modules. At that time, many template styles were also basic table development, and most functions were standard add, delete, change and check

Although the performance of tables is a bit of a problem, that’s in the extreme case of large amounts of data. This article will focus on how to use JS to manipulate the TABLE element in the DOM


Here is a general form prototype:

<table border="1" width="100%">
    <tbody>
        <tr>
            <td>c1-1</td>
            <td>c2-1</td>
        </tr>
        <tr>
            <td>c2-1</td>
            <td>c2-2</td>
        </tr>
    </tbody>
</table>
Copy the code

Tbody is the data display row of our list, composed of several TR’s, representing a row of records; Tr in turn consists of TDS, representing each of the small cells in the row


When operating on a table element, the following attributes and methods are involved:

  • TBodies, an HTMLCollection containing the tBody element
  • THead, refers to tHead element
  • Rows, containing HTMLCollection that represents all rows
  • CreateTHead () creates the thead element, places it in the table, and returns the reference
  • DeleteTHead (), removes thead element
  • DeleteRow (pos), deletes the row at a given position
  • InsertRow (pos) inserts a row at a given position in the row collection

The tBody element is manipulated using the available attributes and methods:

  • Rows, an HTMLCollection containing all the rows in the tBody element
  • DeleteRow (pos), deletes the row at a given position
  • InsertRow (pos), which inserts a row at a given position in the row collection and returns a reference to that row

Attributes and methods for manipulating tr elements:

  • Cells, an HTMLCollection containing all table elements of the TR element
  • DeleteCell (pos) deletes the table element at a given position
  • InsertCell (pos), which inserts a table element at a given position in the table element set and returns a reference to that table element

Now, using the method mentioned above, we insert a table into the DOM as we did at the beginning of this article

Here are a few caveats:

The tBody tag needs to be created with the generic document.createElement.

InsertRow (n); tbody.insertrow (n); To initialize the generated tr tag;

Tbody.rows [n].insertCell(m); To initialize the insertion of td tags

Tbody.rows [n].cells[m] we can clearly know which row and which column we are operating on


In the case of cell merging, it is just changing the colSpan, rowSpan properties on the corresponding TD