How to get a cell Value in table using Javascript

Sirisha picture Sirisha · Aug 20, 2018 · Viewed 7.5k times · Source

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.

Answer

Celica picture Celica · Aug 20, 2018

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>