html - Accessing cell text in Javascript - Stack Overflow

I am trying to change the text of a table cell when only the <table> element has an ID, there are

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

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

Share Improve this question asked Feb 15, 2010 at 15:19 AJ.AJ. 11.3k14 gold badges43 silver badges51 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

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/en/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces

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

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

I remend jQuery strongly. You'll probably get additional responses remending jQuery as well.

Something like that should work:

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

You can do it with pure JS with this code:

document.querySelector('#test td:nth-child(2)').innerHTML = 'value changed';

Browser support for this is pretty god: http://caniuse./#search=querySelector

Edit

Unfortunately @Matt Ball's code is faster as you can see here: JSPerf.

The most obvious way for me is to do it like this code below:

document.getElementById("test").rows[0].cells[1].innerHTML = "Cell not so 2."

http://www.w3schools./jsref/coll_table_cells.asp

If you're dealing with a lot of data, don't use JQuery, as it is slow.

You can look at the passion between JQuery processing and native DOM here (if you follow link in that post, the page has a graph that shows how big the difference is).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745454110a4628407.html

相关推荐

  • html - Accessing cell text in Javascript - Stack Overflow

    I am trying to change the text of a table cell when only the <table> element has an ID, there are

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信