DOM操作表格——HTML DOM

html创建表格:

<table berder='1' width='300'> <thead> <tr> <th>姓名</th> <th>性别</th> <th>年龄</th> </tr> </thead> <tbody> <tr> <th>tzr</th> <th>男</th> <th>24</th> </tr> </tr> </tbody> <tfoot> <tr> <th>结束</th> </tr> </tfoot> </table>

  而利用DOM创建方法为:

window.onload=function(){
    var table=document.createElement('table');
    table.width=300;
    table.border=1;
}

  利用appendChild()方法添加表格的thead、tr,th。如:

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

  可以看出,使用DOM创建表格比较累。

  下面看看如何使用DOM获取表格数据:获取table第一个子节点caption的内容。

window.onload=function(){
    var table=document.getElementByTagName('table')[0];
    alert(table.children[0].innerHTML);
}

  所以,我们常使用HTML DOM。

  table.caption.innerHTML;

  table.caption.innerHTML='人员表';

  table.thead;

  table.tfoot;

  table.tBodies;   //返回tbody集合

  table.rows;    //所有tr集合

  table.tBodies[0].rows;   //主体tbody的tr集合

  table.tBodies[0].rows[1].cells[1].innerHTML;   //返回主体第二行第二个单元格的内容

  table.deleteCaption();

  table.deleteTHead();

  table.tBodies[0].deleteRow(0);    //删除主体第一行

  table.tBodies[0].rows[1].deleteCell(1);   //删除主体第二行第二个数据

  最后,我们可以简单快捷地创建一个表格。

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

  var thead=table.createTHead();

  var tr=thead.insertRow(0);

  tr.insertCell(0).innerHTML='数据1';

  tr.insertCell(1).innerHTML='数据2';

  tr.insertCell(2).innerHTML='数据3';

  PS:在创建表格时,<table>,<tbody>,<th>没有特定的方法。

原文地址:https://www.cnblogs.com/tangzhirong/p/4809551.html