Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get <table> element's nth <td> innerHTML dynamically

Is there anyway I can get the innerHTML of the designated nth <td> in a <table> using JavaSCript?

Since my table is automatically generated, my <td>'s do not have IDs. I am using the following HTML code:

<table id="table">
  <tr>
    <td onmouseover="myTD()">Cell 1</td>
    <td onmouseover="myTD()">Cell 2</td>
    <td onmouseover="myTD()">Cell 3</td
  </tr>
  <tr>
    <td onmouseover="myTD()">Cell 4</td>
    <td onmouseover="myTD()">Cell 5</td>
    <td onmouseover="myTD()">Cell 6</td>
  </tr>
</table>

But how do access, for instance, Cell 5?

Thanks a lot!

like image 880
zdebruine Avatar asked May 27 '26 14:05

zdebruine


2 Answers

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

This will contain all your table cells. Use array notation to access a specific one:

cells[4]

Here's a quick demo which changes the background color:

http://jsfiddle.net/jackwanders/W7RAu/

like image 196
jackwanders Avatar answered May 30 '26 08:05

jackwanders


Not sure what you want - Dom: document.getElementsByTagName("table")[0].rows[2].cells[1]

like image 35
mplungjan Avatar answered May 30 '26 08:05

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!