56

I can't believe how long this has taken me but I can't seem to figure out how to extract a cell value from an HTML table as I iterate through the table with JavaScript. I am using the following to iterate:

  var refTab=document.getElementById("ddReferences")
  var  ttl;
  // Loop through all rows and columns of the table and popup alert with the value
  // /content of each cell.
  for ( var i = 0; row = refTab.rows[i]; i++ ) {
     row = refTab.rows[i];
     for ( var j = 0; col = row.cells[j]; j++ ) {
        alert(col.firstChild.nodeValue);
     }
  }

What is the correct call I should be putting in to the alert() call to display the contents of each cell of my HTML table? This should be in JS...can't use jQuery.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
GregH
  • 12,278
  • 23
  • 73
  • 109
  • What are you seeing? How does your table look like? What browser? I copied your code and ran it against a very simple table and it seemed to work fine. – Lauri Lehtinen Jun 18 '10 at 18:44

12 Answers12

107
function GetCellValues() {
    var table = document.getElementById('mytable');
    for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            alert(table.rows[r].cells[c].innerHTML);
        }
    }
}
user8393645
  • 110
  • 1
  • 1
  • 13
brendan
  • 29,308
  • 20
  • 68
  • 109
  • 5
    Perfect! Thanks a lot. I got textbox value in a cell as follows. var textboxVal = table.rows[r].cells[c].childNodes[0].value; – Sumith Harshan Oct 23 '12 at 12:11
  • 3
    Actually, the above solution is not perfect. You dont get the value in cell but the whole bunch of formating tags as well. – TomeeNS Aug 25 '14 at 13:27
  • 1
    Consider this code, even simpler: document.querySelector("#table").children[0].children[r].children[c].innerText where r is the row index and c the column index – JohnP2 Feb 15 '20 at 18:27
  • PERFECT! nice brendan – andrefilipeos Apr 13 '20 at 15:27
6

I know this is like years old post but since there is no selected answer I hope this answer may give you what you are expecting...

if(document.getElementsByTagName){  
    var table = document.getElementById('table className');
    for (var i = 0, row; row = table.rows[i]; i++) {
    //rows would be accessed using the "row" variable assigned in the for loop
     for (var j = 0, col; col = row.cells[j]; j++) {
     //columns would be accessed using the "col" variable assigned in the for loop
        alert('col html>>'+col.innerHTML);    //Will give you the html content of the td
        alert('col>>'+col.innerText);    //Will give you the td value
        }
      }
    }
}
Suresh
  • 1,491
  • 2
  • 22
  • 27
3

If I understand your question correctly, you are looking for innerHTML:

alert(col.firstChild.innerHTML);
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
3

confer below code


<html>
<script>


    function addRow(){
 var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e =table.rows.length-1;
var l =table.rows[e].cells.length;
//x.innerHTML = "&nbsp;";
 for (var c =0,  m=l; c < m; c++) {
table.rows[0].insertCell(c);
   table.rows[0].cells[c].innerHTML  = "&nbsp;&nbsp;";
}

}




function addColumn(){
       var table = document.getElementById('myTable');
        for (var r = 0, n = table.rows.length; r < n; r++) {
                table.rows[r].insertCell(0);
                table.rows[r].cells[0].innerHTML =  "&nbsp;&nbsp;" ;

        }

    }

function deleteRow() {
    document.getElementById("myTable").deleteRow(0);

}

function deleteColumn() {
   // var row = document.getElementById("myRow");
 var table = document.getElementById('myTable');
 for (var r = 0, n = table.rows.length; r < n; r++) {
    table.rows[r].deleteCell(0);//var table handle 
}
}

</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0       style='cursor:hand'>
    <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
    <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
    <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>

    <table  id='myTable' border=1 cellpadding=0 cellspacing=0>
 <tr id='myRow'>          
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
<tr>          
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>

    </table>



</body>
</html>

pota opt
  • 91
  • 1
  • 1
2

the above guy was close but here is what you want:

       var table = document.getElementById(tableID);
       var rowCount = table.rows.length;        
         for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            alert(table.rows[r].cells[c].firstChild.value);
        }
    }
        }catch(e) {
            alert(e);
        }
Jamie Krcmar
  • 119
  • 1
  • 3
2

The code yo have provided runs fine. Remember that if you have your code in the header, you need to wait for the dom to be loaded first. In jQuery it would just be as simple as putting your code inside $(function(e){...});

In normal javascript use window.onLoad(..) or the like... or have the script after the table defnition (yuck!). The snippet you provided runs fine when I have it that way for the following:

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title></title>
</head>
<body>
  <table id='ddReferences'>
    <tr>
      <td>dfsdf</td> 
      <td>sdfs</td>
      <td>frtyr</td>
      <td>hjhj</td>
    </tr>
  </table>

<script>
var refTab = document.getElementById("ddReferences")
var  ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
   row = refTab.rows[i];
   for ( var j = 0; col = row.cells[j]; j++ ) {
      alert(col.firstChild.nodeValue);
   }
}

</script>
</body>
</html>
Java Drinker
  • 3,127
  • 1
  • 21
  • 19
1

If you are looking for the contents of the TD (cell), then it would simply be: col.innerHTML

I.e: alert(col.innerHTML);

You'll then need to parse that for any values you're looking for.

Michael Fredrickson
  • 36,839
  • 5
  • 92
  • 109
Ben Madsen
  • 101
  • 1
  • 4
0

Have you tried innerHTML?

I'd be inclined to use getElementsByTagName() to find the <tr> elements, and then on each to call it again to find the <td> elements. To get the contents, you can either use innerHTML or the appropriate (browser-specific) variation on innerText.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

A few problems:

  • The loop conditional in your for statements is an assignment, not a loop check, so it might infinite loop

  • You should use the item() function on those rows/cells collections, not sure if array index works on those (not actually JS arrays)

  • You should declare the row/col objects to ensure their scope is correct.

Here is an updated example:

var refTab=document.getElementById("ddReferences") 
var  ttl; 
// Loop through all rows and columns of the table and popup alert with the value 
// /content of each cell. 
for ( var i = 0; i<refTab.rows.length; i++ ) { 
  var row = refTab.rows.item(i); 
  for ( var j = 0; j<row.cells.length; j++ ) { 
    var col = row.cells.item(j);
    alert(col.firstChild.innerText); 
  } 
}

Replace innerText with innerHTML if you want HTML, not the text contents.

David
  • 2,785
  • 1
  • 16
  • 8
0

Guess I'm going to answer my own questions....Sarfraz was close but not quite right. The correct answer is:

alert(col.firstChild.value);
GregH
  • 12,278
  • 23
  • 73
  • 109
  • Sorry, actually Safraz was right. I had to add "firstChild" because in my actual code I have a text input element in the cell so technically he is right. – GregH Jun 18 '10 at 22:14
0

Try this out: alert(col.firstChild.data)

Check this out for the difference between nodeValue and data: When working with text nodes should I use the "data", "nodeValue", "textContent" or "wholeText" field?

KaliCharan
  • 1,215
  • 2
  • 8
  • 12
-2
<script>
    $('#tinh').click(function () {
        var sumVal = 0;
        var table = document.getElementById("table1");

        for (var i = 1; i < (table.rows.length-1); i++) {
            sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
        }


        document.getElementById("valueTotal").innerHTML = sumVal;
    });
</script>
Dung
  • 1