views:

36

answers:

3

Hello,

I am trying to change the text of a table cell when only the <table> element has an ID, there are no IDs set on the cells, e.g.

<table id="test">
  <tbody>
    <tr>
      <td>Cell 1</td>
      <td>Cell 2</td>
    </tr>
  </tbody>
</table>

So how do I change the text of the second cell (Cell 2) in Javascript without explicitly specifying an ID for it?

Thanks,

AJ

A: 

Using jQuery, this task would be as simple as the following:

$('#test td:first').text('Your new text goes here');

I recommend jQuery strongly. You'll probably get additional responses recommending jQuery as well.

Drew Wills
Drew, the OP said second, not first.
Matt Ball
Whoops -- missed that. In that case, the selector would be: '#test td:eq(1)'
Drew Wills
+5  A: 

It's really easy to do with jQuery, but I'm assuming you want to use native DOM methods. In that case,

document.getElementById('test').getElementsByTagName('td')[1]

will get you to the 2nd table cell in that table.

https://developer.mozilla.org/en/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces

Matt Ball
That's perfect, thank you!
AJ
No problem. I'd still recommend using jQuery because it makes your code much more concise, reduces boilerplate, and just makes writing Javascript much less hellish.
Matt Ball
A: 

Something like that should work:

document.getElementById('test').childNodes[1].childNodes[1].childNodes[3].innerHTML='changed cell';
skyman