最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get cell value from a dynamic table in HTML - Stack Overflow

programmeradmin1浏览0评论

I use Javascript to dynamically add new row to a html table, then I used:

var table = document.getElementById(tableID);
var rowCount = table.rows.length;
queue.innerHTML +=table.rows[rowCount].cells[1].firstChild.nodeValue + "/" +  table.rows[rowCount].cells[2].firstChild.nodeValue +"\n";

But it only returned null, thus I wonder that can we get value from cells form row which was dynamically added and how? Thank you.

I use Javascript to dynamically add new row to a html table, then I used:

var table = document.getElementById(tableID);
var rowCount = table.rows.length;
queue.innerHTML +=table.rows[rowCount].cells[1].firstChild.nodeValue + "/" +  table.rows[rowCount].cells[2].firstChild.nodeValue +"\n";

But it only returned null, thus I wonder that can we get value from cells form row which was dynamically added and how? Thank you.

Share asked Apr 22, 2011 at 8:07 TLDTLD 8,14528 gold badges95 silver badges132 bronze badges 1
  • 1)Where does queue e from? 2)rowCount is the amount of rows +1, so your logic can't be really right for grabbing something. 3)We need to know your html structure. 4)JavaScript doesn't care if the nodes were dynamically created or not. It just cares that they exist when the code executes. See jsfiddle/9pL23 – Zirak Commented Apr 22, 2011 at 8:15
Add a ment  | 

3 Answers 3

Reset to default 1

I don't think nodeValue is the right thing to use. Per this the nodeValue of an element is always null.

If you are dynamically creating the table rows, wouldn't it make more sense to add it to queue.innerHTML at the same time instead of doing it this way?

I think the rows collection is a zero based array like structure. So try using rowCount-1:

queue.innerHTML += table.rows[rowCount-1].cells[1].firstChild.nodeValue 
                   + "/" +  
                   table.rows[rowCount-1].cells[2].firstChild.nodeValue +"\n";

Furthermore, you can use innerText, as in table.rows[rowCount-1].cells[1].innerText to get the cell value

[edit] skip the rowCount part: you are assigning it before the addition, so rowCount should work. You should read this though, because innerHTML for tables doesn't always give the desired results.

Here's how I'd do it with jQuery, if I understand your question correctly.

<script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
  var $lastRow = $('table tr:last');
  queue.innerHTML += $lastRow.find('td:eq(1)') + '/' + $lastRow.find('td:eq(2)')
</script>

Or :eq(0) and :eq(1) if you want the first and second cell.

发布评论

评论列表(0)

  1. 暂无评论