Link to home
Start Free TrialLog in
Avatar of LarryAndro
LarryAndro

asked on

Table Cell InnerHTML and <P> Corruption

I am looping thru a table, cell by cell, evaluating the innerHTML-derived contents.  Everything works fine for simple cells...  <td>B</td>.  But, when I come to a <td><p ....>B</p></td> cell, containing <p>...</p>, strange things happen.  But, definitely, 'B' is not returned!  

How can I get innerHTML to return 'B' only?

Just in case the above question doesn't make sense, I'm including below my HTML I created to test this problem...

<html>
<head>

<script>

      function MakeSubArray(tableNm){
            document.write("<br>TABLE: "+tableNm);
            var table, rowNo, colNo, cellTxt;
            var tableArr = new Array();
            var table=document.getElementById(tableNm);
            var tableLen=table.rows.length;
            for(rowNo=0;rowNo<tableLen;rowNo++){
                  document.write("     row#:"+rowNo+"        ");
                  for(colNo=0;colNo<2;colNo++){
                        document.write(".");
                        cellTxt=table.rows[rowNo].cells[colNo].innerHTML;
                        document.write("   cell#:"+colNo+"["+cellTxt+"]");
                  }                  
            }      
        }
        
        
</script>

</head>
<body>

'table1' here...
<table id="table1" >
      <tr>
            <td>A</td>
            <td>B</td>
      </tr>
</table>

<br>'table2' here...
<table id="table2" >
      <tr>
            <td>A</td>
            <td><p>B</p></td>
      </tr>
</table>

<br><br>Calling MakeSubArray to print cell contents...

<script>
      MakeSubArray("table1");
      MakeSubArray("table2");
</script>

</table>
</body>
</html>

Running the above gives...

'table1' here...
A B

'table2' here...
A B
 
Calling MakeSubArray to print cell contents...
TABLE: table1 row#:0 . cell#:0[A]. cell#:1[B]               <--B prints fine for table1...
TABLE: table2 row#:0 . cell#:0[A]. cell#:1[                  <--notice cell#1 corruption..
B                                                                               <--
                                                                                <--
]
ASKER CERTIFIED SOLUTION
Avatar of GwynforWeb
GwynforWeb
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
this is  better cleaner

cellTxt=table.rows[rowNo].cells[colNo].innerHTML
cellTxt=cellTxt.replace(/<[^><]+>/g,'')
Avatar of LarryAndro
LarryAndro

ASKER

Thanks...
Thanks for the good question - your code included was very helpful to me.
I depend so much on the questions on this site.  Good to know that one of my questions, and the answer, was useful to someone else!