1

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.

1

2 Answers 2

2

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!! :)

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.