Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript reverse engineering: Convert html table to string/text

Currently I have a table variable which I want to get its table content in this way: <table><tr></tr></table> instead of getting a Javascript object. Is there a solution to finding a method that could do that?

like image 350
pivotal developer Avatar asked Jul 30 '26 22:07

pivotal developer


2 Answers

try innerHTML.

like image 188
strauberry Avatar answered Aug 01 '26 11:08

strauberry


This assumes your table is the only table on the page. If this is not the case, give it a unique ID (such as tableID) and reference using getElementsById("tableID").

var tables = document.getElementsByTagName("table");
var firstTable = tables[0];
var tableAttr = firstTable.attributes;
// get the tag name 'table', and set it lower case since JS will make it all caps
var tableString = "<" + firstTable.nodeName.toLowerCase() + ">";
// get the tag attributes
for(var i = 0; i < tableAttr.length; i++) {
    tableString += " " + tableAttr[i].name + "='" + tableAttr[i].value + "'";
}

// use innerHTML to get the contents of the table, then close the tag
tableString += firstTable.innerHTML + "</" +
    firstTable.nodeName.toLowerCase() + ">";

// table string will have the appropriate content

You can see this in action in a short demo.

The pertinent things to learn are:

  • getElementsByTagName - get DOM elements by their tag name
  • attributes - a DOM property that gets an attributes array
  • innerHTML - gets a string of the HTML inside any DOM object
  • nodeName - gets the name of any DOM object

If you get into using a framework, jquery's .html() method and the getAttributes plugin would potentially also be helpful

like image 39
justkt Avatar answered Aug 01 '26 11:08

justkt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!