0

I have a table, I want to print all inner html of table cells when I click on any cell, If I do this through button it's working fine but when I do this with click on cell it's throwing an error Uncaught TypeError: Cannot read property 'innerHTML' of undefined.

function funcName(){
   var allTds = document.getElementsByTagName("td");
  for(var j=0; j<allTds.length;j++){  
        allTds[j].onclick = function(){
            var chekTds = allTds[j].innerHTML;
                console.log(chekTds);                
    }   
}   

2 Answers2

1

Change to this...

    function funcName() {
    var allTds = document.getElementsByTagName("td");
    for (var j = 0; j < allTds.length; j++) {
        allTds[j].onclick = function() {
            var allTdsNew = document.getElementsByTagName("td");
            for (var k = 0; k < allTdsNew.length; k++) {
                console.log(allTdsNew[k].innerHTML);
                     }

                   }

               }
           }
Anand Singh
  • 2,343
  • 1
  • 22
  • 34
0

You have onclick in you function. check this code.

<script>
function wokring(){
   var allTds = document.getElementsByTagName("td");
  for(var j=0; j<allTds.length;j++){  
        var chekTds = allTds[j].innerHTML;
            alert(chekTds);                
    }
} 
</script>
<table>
    <tr>
        <td onclick="wokring()">1</td>
        <td  onclick="wokring()">2</td>
    </tr>   
</table>

remove this line....

allTds[j].onclick = function(){
M Razwan
  • 257
  • 3
  • 12