Thursday, December 17, 2009

Traversing an Html table with Javascript

This article will introduce you on how to get html table content using DOM Inteface, ones we create an Table on html and suppose we need to retive that table content on server side, on any purpose then this will helps can refer this its really nice way to parse the html table and get the content on same .

mozilla developer has given a good link on ,how to create a DOm interface for table structure

sample example:
1. lets create a Table

<tr> <td> This is first td </td></tr>
<tr> <td> This is second td </td></tr>
<tr> <td> This is third td </td></tr>

2. now create a Dom inteface to read this table content , for that you can use Javascript to read this

<script >
function start() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];

// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");

// creating all cells
for (var j = 0; j < 2; j++) {
// creates a table row
var row = document.createElement("tr");

for (var i = 0; i < 2; i++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row "+j+", column "+i);

// add the row to the end of the table body

// put the <tbody> in the <table>
// appends <table> into <body>
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
</script >

3. This javascript will first read the table tag element and search with tbody and tr then next td and retrive the content on same .

4. Remember this technique. You will use it frequently in programming for the W3C DOM. First, you create elements from the top down; then you attach the children to the parents from the bottom up.

5. Its create just like this way .

1 comment:

  1. thank you very much for the instruction. you helped me a lot. i hope it will solve my problems.