开发者

Create a table row in between 2 rows using javascript?

How can I create a table row in between 2 ? I am using the code below to create a row.

 if (!document.getElementsByTagName) return;
         tabBody=document.getElementsByTagName("TBODY").item(0);

         row=document.createElement("TR");

         cell1 = document.createElement("TD");

         textnode1=document.createTextNode('');

         cell1.appendChild(textnode1);


         row.appendChild(cell1);

         tabBody.appendChild(row);


}

Actually I want to create it as a middle row. Currently my table has 2 rows. 开发者_运维问答


A table exposes its own methods that can be used to modify it:

- insertRow 
- deleteRow

A table row exposes a method that can be used to insert a new cell: insertCell.
Here are some basic examples.


Table elements have their own methods for manipulating them, so you can use the .insertRow() method and the .insertCell()

var table = document.getElementsByTagName('table')[0];
var middleRow = table.insertRow( Math.floor( table.rows.length / 2 ) );
var cell1 = middleRow.insertCell(0);
var textnode1=document.createTextNode('');
cell1.appendChild( textnode1 );

demo http://jsfiddle.net/gaby/yA7Rg/


try using insertBefore; begin by calculating the index of middle row then insertBefore the nextSibling to get the row to the right index

tabBody.insertBefore(row, tabBody.childNodes[0].nextSibling);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜