User12341234
User12341234

Reputation: 79

How to get a cell Value in table using Javascript

I have written this function to get cell values of a table in Javascript. Using innerHTML is returning cell value along with HTML code.Going through some forums got to know innerText should be used to get value of the cell.But it is returning empty in my condition.

Below is the Script i am using.

function validateMyFunction() {
    var sTableName = document.getElementById("tablename");
    alert("sTableName>>>>>>>>>>"+sTableName);
    alert("sTableName>>>>>>>>>>"+sTableName.rows.length);
    for (var i=0;i<sTableName.rows.length;i++) {
        var col1= sTableName.rows[i].cells[11].innerText;
        var col2= sTableName.rows[i].cells[9].innerText;
    }
}

Can anyone please help with any alternatives for this.

Thanks.

Upvotes: 1

Views: 13372

Answers (2)

Mahesh Yadav
Mahesh Yadav

Reputation: 388

You can use following code to get the cells value of table

var sTableName = document.getElementById("tablename");
for(var i=0;i<sTableName.children[0].childElementCount;i++) 
{
  var tableRow = sTableName.children[0].children[i];
  for(var j=0;j<tableRow.childElementCount;j++)
  {
    var tableColumn = tableRow.children[j];
    console.log('Cell ['+i+','+j+'] value: '+tableColumn.innerText);
  }
}

use the above code snippet in your function and you can user tableColumn.innerText to validate its value.

Enjoy Scripting!! :)

Upvotes: 2

Celica
Celica

Reputation: 41

do you have values in those locations? Works for me ok using this example:

<table id="tablename">
    <tr>
        <td>hi!</td>
    <tr>
</table>
<button onclick="showCell()">Show Cell Value</button>

<script>
function showCell() {
    var sTableName = document.getElementById("tablename");

    for (var i=0;i<sTableName.rows.length;i++) {
        var col1= sTableName.rows[i].cells[0].innerText;
        alert(col1)
    }
}
</script>

Upvotes: 2

Related Questions