1

I'm working on a way to export some tabular data from an HTML page to Excel using a program called DocRaptor. I'm using PHP to pass the data using their API which then converts the data to an Excel Spreadsheet.

I can't however seem to pass the whole table (including the opening <table> and closing </table> tags.

Say for example if I have the following table in HTML:

<table id="placement-table">
    <tr id="row">
    <td id="cell">Text1</td>
    </tr>
<tr id="row1">
    <td id="cell">Text2</td>
    </tr>
<tr id="row2">
    <td id="cell">Text3</td>
    </tr>
<tr id="row3">
    <td id="cell">Text4</td>
    </tr>
</table>

Now for example if I use console.log($('#placement-table').html()); I only get the following output:

<tbody><tr id="row">
    <td id="cell">Text1</td>
    </tr>
    <tr id="row1">
    <td id="cell">Text2</td>
    </tr><tr id="row2">
    <td id="cell">Text3</td>
    </tr><tr id="row3">
    <td id="cell">Text4</td>
    </tr>
</tbody>

Why am I missing the actual opening and closing <table></table> tags? Is it because .html() only gives you the content inside of the given element? I realise I'm only logging the info to the Console but I'm just doing this so I can see what's being passed and hence why I noticed it was missing these tags.

Hope this makes sense, if not I can update the question!

zik
  • 3,035
  • 10
  • 41
  • 62
  • relatively to jquery documentation , the .html() method gives you onlly the html content http://api.jquery.com/html/ – fatiDev Sep 17 '12 at 11:47

4 Answers4

3

You can use outerHTML:

$('#placement-table')[0].outerHTML

or:

var table = document.getElementById('placement-table').outerHTML

http://jsfiddle.net/eQRL3/

Ram
  • 143,282
  • 16
  • 168
  • 197
1

From Get selected element's outer HTML

(function($) {
  $.fn.outerHTML = function() {
    return $(this).clone().wrap('<div></div>').parent().html();
  }
})(jQuery);

console.log($('#placement-table').outerHTML());    // <table>...</table>
Community
  • 1
  • 1
Andreas
  • 21,535
  • 7
  • 47
  • 56
0

Correct; html() gets the content of the element you supply, and not the container itself. Simplest solution would be to add a wrapper div...

MassivePenguin
  • 3,701
  • 4
  • 24
  • 46
0

Method html gets the innerHTML of the element. You should use something like outerHTML, which in jQuery can be done as follows:

var table = $("#placement-table").clone().wrap("<div />").parent().html();
console.log(table);
VisioN
  • 143,310
  • 32
  • 282
  • 281