6

I am trying to get the table html in Jquery.

I have the following:

<table id='table' border='1'>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
</table>

I have

var test = $('#table').html()

but when i console.log(test) i got

<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>

without <table> tags.

Is there anyway to fix this? Thanks a lot!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

3 Answers3

20

A more jQuery oriented approach would be to retrieve the outerHtml property from the table.

 $('#table').prop('outerHTML')
Stieffers
  • 752
  • 3
  • 13
3

One option is:

document.getElementById('table').outerHTML;

JS Fiddle demo.

Or, you could instead:

$('<div />').html($('#table').clone()).html();

JS Fiddle demo.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • +1 for not using jQuery if it isn't necessary. If you'd like to use it in jQuery: `var table = document.getElementById('table').outerHTML;` `var jqueryTable = $(table);` – Luuuud Oct 29 '13 at 19:29
0

Another option is to wrap the table in something else, then get the html() of that element instead.

Example Markup:

<div class="wrapper">
    <table id='table' border='1'>
        <tr><td>items...</td><td>items2...</td></tr>
        <tr><td>items...</td><td>items2...</td></tr>
        <tr><td>items...</td><td>items2...</td></tr>
        <tr><td>items...</td><td>items2...</td></tr>
    </table>
</div>

And the jQuery:

var table = $('.wrapper').html();

You should probably just use @David Thomas' answer though.

grammar
  • 871
  • 10
  • 22