JavaScript study notes (13) Dom creation table_basic knowledge
WBOY
Release: 2016-05-16 18:36:10
Original
1064 people have browsed it
Dom basics - creating tables There are two formats for dynamically creating tables using js, appendChild() and insertRow and insertCell(). However, the first method may have problems on IE, so it is recommended to use the second method. 1. insertRow(index): index starts from 0 This function adds a new row before the row of index, such as insertRow(0), which adds a new row before the first row. The default insertRow() function is equivalent to insertRow(-1), which adds a new row to the end of the table. Generally when we use it: objTable.insertRow (objTable.rows.length) is to add a new row at the end of the table objTable. The usage of insertCell() and insertRow is the same. 2. deleteRow(index): index starts from 0 Delete the row at the specified position. The parameter to be passed in: Index is the position of the row in the table. It can be obtained by the following method and then deleted: var row = document.getElementById("row's Id"); var index = row.rowIndex; //There is this attribute objTable.deleteRow(index); During use, delete the table's When rowing, if a certain row is deleted, the number of rows in the table will change immediately, and rows.length is always getting smaller, so if you want to delete all rows in the table:
function removeAllRow() { var objTable = document.getElementById("myTable"); var length = objTable.rows.length; for (var i = 1; i < length; i ) { objTable.deleteRow(i); } }
3. The setAttribute() method dynamically sets the attributes of cells and rows The format is as follows: setAttribute (attribute, attribute value) var objMyTable = document.getElementById("myTable"); objMyTable.setAttribute("border", 1); //Set the border for the table to 1 I encountered a problem with setting the style when using it. I cannot use setAttribute("class", "inputbox1"); Instead, you should use setAttribute("className", "inputbox1"), 4. Create a table Once you understand the addition and deletion of rows
and cells
, you can create a table. Step one: You need to have a table that you want to dynamically change. Here we are talking about tables that already exist on the page. We set an id: myTable var objMyTable = document.getElementById("myTable"); Step 2: Create row and column objects
var index = objMyTable.rows.length; var nextRow = objMyTable.insertRow(index); //In the last row //var nextRow = objMyTable.insertRow(0); //In the first row
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn