开发者

Accessing cell text in Javascript

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


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


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.


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.com/#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.com/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 compassion 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜