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>
inst开发者_如何学JAVAead of getting a Javascript object. Is there a solution to finding a method that could do that?
try innerHTML.
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
Try following code...
<html>
<head>
<script type="text/javascript">
function sample_function(){
alert(document.getElementById('div_first').innerHTML);
}
</script>
</head>
<body>
<div id="div_first">
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table></div>
<button onclick="sample_function()">Click Here</button>
</body>
</html>
精彩评论