DOM操作表格及样式

209 阅读1分钟

DOM操作表格及样式

一.操作表格

  1. HTML表格
<table border="1" width="300">
  <caption>人员表</caption>
  <thead>
    <tr>
      <th>姓名</th>
      <th>性别</th>
      <th>年龄</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>张三</td>
      <td></td>
      <td>20</td>
    </tr>
    <tr>
      <td>李四</td>
      <td></td>
      <td>22</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3">合计:N</td>
    </tr>
  </tfoot>
</table>
  1. DOM创建表格
var table = document.createElement('table');
table.border = 1;
table.width = 300;

var caption = document.createElement('caption');
table.appendChild(caption);
caption.appendChild(document.createTextNode('人员表'));

var thead = document.createElement('thead');
table.appendChild(thead);

var tr = document.createElement('tr');
thead.appendChild(tr);

var th1 = document.createElement('th');
var th2 = document.createElement('th');
var th3 = document.createElement('th');

tr.appendChild(th1);
th1.appendChild(document.createTextNode('姓名'));
tr.appendChild(th2);
th2.appendChild(document.createTextNode('年龄'));

document.body.appendChild(table);

3.HTML DOM创建表格

var table = document.createElement('table');
table.border = 1;
table.width = 300;

table.createCaption().innerHTML = '人员表';

//table.createTHead();
//table.tHead.insertRow(0);
var thead = table.createTHead();
var tr = thead.insertRow(0);

var td = tr.insertCell(0);
td.appendChild(document.createTextNode('数据'));

var td2 = tr.insertCell(1);
td2.appendChild(document.createTextNode('数据 2'));

document.body.appendChild(table);

微信图片_20210706095227.png

微信图片_20210706095301.png

二.操作样式