2

I would like to load all table elements from my index.html which have the specified class assigned in a variable. Unfortunately the first line of HTML doesn't load correctly.

My HTML (example for one table, usually there a few of them):

<!-- More HTML stuff -->
<table class="class_TopTable table" id="id_TopTable">
  <tr>
    <td>
      <button id="id_Remove">Remove 1</button>
    </td>
    <td>
      <div id="id_Title"><B>Title 1</B></div>
      <div id="id_Content">Content 1</div>
    </td>
  </tr>
</table>
<!-- More HTML stuff -->

My Javascript:

var all_class_TopTable = "";
$('.class_TopTable').each(function(){
      all_class_TopTable += $(this).html();
})

After this JS is run, the variable of all_class_TopTable containts following HTML:

<tbody>
  <tr>
    <td>
      <button id="id_Remove">Remove 1</button>
    </td>
    <td>
      <div id="id_Title"><B>Title 1</B></div>
      <div id="id_Content">Content 1</div>
    </td>
  </tr>
</tbody>

Where the first line is different as my real html. I expect in the beginning <table class="class_TopTable table" id="id_TopTable"> and in the end </table>.

But the result is in the beginning <tbody> and in the end </tbody>.

What do I wrong?

1
  • Tables contain thead, tfoot and tbody elements. If you do not specify, than whatever rows that are in the table are in the tbody element. You are reading the HTML of the table so it selects all the children, hence why you get tbody. If you want the table tag, than you need to read the outerHTML. Commented Jan 7, 2019 at 21:28

2 Answers 2

3

You are getting the inner HTML of the table node(s), which excludes the table node(s) itself.

You could wrap all the content in a div and then get its html:

var all_class_TopTable = $('<div>').append($('.class_TopTable').clone()).html();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, now I know why it doesn't work and how to solve it.
1

You could use the outerHTML property to capture the element itself along with its descendants.

all_class_TopTable += $(this)[0].outerHTML;

As the html method only captures its descendants, it wraps it with tbody.

2 Comments

Note that it is not the html method that wraps it with tbody. tbody is added at the moment the DOM is built.
@trincot Good point. Looks like I interpreted it incorrectly.

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.