How to get html table td cell value by JavaScript?

user661684 picture user661684 · Apr 7, 2012 · Viewed 143.2k times · Source

I have an HTML table created with dynamic data and cannot predict the number of rows in it. What I want to do is to get the value of a cell when a row is clicked. I know to use td onclick but I do not know how to access the cell value in the Javascript function.

The value of the cell is actually the index of a record and it is hidden in the table. After the record key is located I can retrieve the whole record from db.

How to get the cell value if I do not know the row index and column index of the table that I clicked?

Answer

Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var i=0,len=cells.length; i<len; i++){
    cells[i].onclick = function(){
        console.log(this.innerHTML);
        /* if you know it's going to be numeric:
        console.log(parseInt(this.innerHTML),10);
        */
    }
}

var table = document.getElementById('tableID'),
  cells = table.getElementsByTagName('td');

for (var i = 0, len = cells.length; i < len; i++) {
  cells[i].onclick = function() {
    console.log(this.innerHTML);
  };
}
th,
td {
  border: 1px solid #000;
  padding: 0.2em 0.3em 0.1em 0.3em;
}
<table id="tableID">
  <thead>
    <tr>
      <th>Column heading 1</th>
      <th>Column heading 2</th>
      <th>Column heading 3</th>
      <th>Column heading 4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>43</td>
      <td>23</td>
      <td>89</td>
      <td>5</td>
    </tr>
    <tr>
      <td>4</td>
      <td>3</td>
      <td>0</td>
      <td>98</td>
    </tr>
    <tr>
      <td>10</td>
      <td>32</td>
      <td>7</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

JS Fiddle proof-of-concept.

A revised approach, in response to the comment (below):

You're missing a semicolon. Also, don't make functions within a loop.

This revision binds a (single) named function as the click event-handler of the multiple <td> elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):

function logText() {
  // 'this' is automatically passed to the named
  // function via the use of addEventListener()
  // (later):
  console.log(this.textContent);
}

// using a CSS Selector, with document.querySelectorAll()
// to get a NodeList of <td> elements within the #tableID element:
var cells = document.querySelectorAll('#tableID td');

// iterating over the array-like NodeList, using
// Array.prototype.forEach() and Function.prototype.call():
Array.prototype.forEach.call(cells, function(td) {
  // the first argument of the anonymous function (here: 'td')
  // is the element of the array over which we're iterating.

  // adding an event-handler (the function logText) to handle
  // the click events on the <td> elements:
  td.addEventListener('click', logText);
});

function logText() {
  console.log(this.textContent);
}

var cells = document.querySelectorAll('#tableID td');

Array.prototype.forEach.call(cells, function(td) {
  td.addEventListener('click', logText);
});
th,
td {
  border: 1px solid #000;
  padding: 0.2em 0.3em 0.1em 0.3em;
}
<table id="tableID">
  <thead>
    <tr>
      <th>Column heading 1</th>
      <th>Column heading 2</th>
      <th>Column heading 3</th>
      <th>Column heading 4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>43</td>
      <td>23</td>
      <td>89</td>
      <td>5</td>
    </tr>
    <tr>
      <td>4</td>
      <td>3</td>
      <td>0</td>
      <td>98</td>
    </tr>
    <tr>
      <td>10</td>
      <td>32</td>
      <td>7</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

JS Fiddle proof-of-concept.

References: