2

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?

0

3 Answers 3

8

try innerHTML.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.