admin管理员组文章数量:1289900
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?
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?
3 Answers
Reset to default 8try 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>
本文标签: Javascript reverse engineering Convert html table to stringtextStack Overflow
版权声明:本文标题:Javascript reverse engineering: Convert html table to stringtext - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741401053a2376668.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论