faqts : Computers : Programming : Languages : JavaScript : Tables

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

117 of 129 people (91%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I read a table cell's content?

Apr 3rd, 2000 10:16
Martin Honnen, Nick Lamb,


NN6 and IE4+ allow full DOM access and thereby access to the content of 
a TABLE cell by scriping the HTMLTableCellElement and its child nodes.
A cell itself is scriptable by various means:
  - as the 
      this
    object in the cells event handlers
  - by IDing it and accessing
      document.all['cellID']
    respectively
      document.getElementById('cellID')
  - through the rows/cells collection of a table element and its rows:
      tableReference.rows[rowIndex].cells[cellIndex]
 
Note however that a cell can contain complex html elements like a 
complete table itself so there is at least in NN6 no api call to 
manipulate somethink like a cell's value. IE4+ has the innerText and 
innerHTML properties which flatten the DOM tree structure contained in 
a cell to a string. If you are sure there is a text node in your cell 
you can with NN6 access
  cellReference.firstChild.nodeValue
to read the text. The following is an example for that:

<HTML>
<HEAD>
<SCRIPT>
function getCellValue (cellOrId) {
  var cell = 
    typeof cellOrId == 'string' ? 
      (document.all ? document.all[cellOrId] : document.getElementById
(cellOrId)) :
      cellOrId;
  if (document.all)
    return cell.innerText;
  else {
    cell.normalize();
    if (cell.firstChild.nodeType == 3)
      return cell.firstChild.nodeValue;
    else 
      return '';
  }
}
</SCRIPT>
</HEAD>
<BODY>
<A HREF="javascript: alert(getCellValue ('aCell')); void 0">
show cell value of cell named aCell
</A>
|
<A HREF="javascript: var table = document.all ?
                       document.all['aTable'] :
                       document.getElementById('aTable');
                     alert(getCellValue(table.rows[2].cells[0])); 
                     void 0"
>
show cell value of cell 0 in row 2 (indices starting with 0)
</A>
<BR>
<TABLE ID="aTable" BORDER="1">
<TR>
<TD ONCLICK="alert(getCellValue(this));">
JavaScript.FAQTs.com
</TD>
</TR>
<TR>
<TD ID="aCell">
Kibology
</TD>
</TR>
<TR>
<TD>
Scriptology
</TD>
</TR></TABLE>
</BODY>
</HTML>