DOM中操作表格的属性和方法

  HTML DOM中对于操作表格内置了一系列的属性和方法,通过js可以方便的创建表格。

caption<caption>的指针
tBodies<tbody>的HTMLCollection(类数组搜集对象)
tFoot<tfoot>的指针
tHead<thead>的指针
rows保存所有行的HTMLCollection
createTHead()创建<thead>的方法,返回引用
createTFoot()创建<tfoot>的方法,返回引用
createCaption()创建<caption>的方法,返回引用
deleteTFoot()删除<tfoot>
deleteTHead()删除<thead>
deleteCaption()删除<caption>
deleteRow(pos)删除行
insertRow(pos)插入行
cells保存<tr>中单元格的HTMLCollection

 

如下为使用这种方式来创建一个表格和直接操作DOM来创建一个表格对比:

        // js 操作dom
//        var body = document.documentElement;
        var body = document.body;
        var table = document.createElement("table");
        table.setAttribute("border", "1");
        table.setAttribute("width", "100%")
        body.appendChild(table);
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);

        var tr1 = document.createElement("tr");
        tbody.appendChild(tr1);
        var cell1_1 = document.createElement("td");
        cell1_1.appendChild(document.createTextNode("cell 1, 1"));
        tr1.appendChild(cell1_1);
        var cell1_2 = document.createElement("td");
        cell1_2.appendChild(document.createTextNode("cell 1, 2"));
        tr1.appendChild(cell1_2);
        var tr2 = document.createElement("tr");
        tbody.appendChild(tr2);
        var cell2_1 = document.createElement("td");
        cell2_1.appendChild(document.createTextNode("cell 2, 1"));
        tr2.appendChild(cell2_1);
        var cell2_2 = document.createElement("td");
        cell2_2.appendChild(document.createTextNode("cell 2, 2"));
        tr2.appendChild(cell2_2);

        body.appendChild(document.createElement("br"));
        body.appendChild(document.createElement("hr"));
        body.appendChild(document.createElement("br"));

        // DOM 表格属性方法使用
        var table2 = document.createElement("table");
        table2.setAttribute("border", "1");
        table2.setAttribute("width", "100%")
        body.appendChild(table2);
        var tbody2 = document.createElement("tbody");
        table2.appendChild(tbody2);

        tbody2.insertRow(0);  // 插入第一行
        tbody2.rows[0].insertCell(0);  // 插入行中第一个格
        tbody2.rows[0].cells[0].appendChild(document.createTextNode("cell 1, 1"));
        tbody2.rows[0].insertCell(1);  // 插入行中第二个格
        tbody2.rows[0].cells[1].appendChild(document.createTextNode("cell 1, 2"));

        tbody2.insertRow(1);  // 插入第二行
        tbody2.rows[1].insertCell(0);
        tbody2.rows[1].cells[0].appendChild(document.createTextNode("cell 2, 1"));
        tbody2.rows[1].insertCell(1);
        tbody2.rows[1].cells[1].appendChild(document.createTextNode("cell 2, 2"));

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值