Javascript Element How to - Convert html table to string/text








Question

We would like to know how to convert html table to string/text.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!-- ww w .j  a v  a 2  s.  c  o  m-->
var tables = document.getElementsByTagName("table");
var firstTable = tables[0];
var tableAttr = firstTable.attributes;

var tableString = "<" + firstTable.nodeName.toLowerCase();

for (var i = 0; i < tableAttr.length; i++) {
    tableString += " " + tableAttr[i].name + "='" + tableAttr[i].value + "'";
}

tableString += ">" + firstTable.innerHTML + "</" + firstTable.nodeName.toLowerCase() + ">";
console.log(tableString);

}
</script>
</head>
<body>
  <table border="0">
    <tr>
      <th></th>
    </tr>
    <tr>
      <td></td>
    </tr>
  </table>
</body>
</html>

The code above is rendered as follows: