1

My HTML and JavaScript code look like this:

<html>
<!--...
many code 
...-->
    <button onclick="alert($('#mytable').html().wrap('<html/>') );">Show HTML Table</button>

    <table id="myTable">

        <tr's and td's>
    </table>
<!--...
many code
...-->
</html>

I want my javascript to return the table wrapped by the HTML tags but I do not want the table itself to be changed.

double-beep
  • 5,031
  • 17
  • 33
  • 41
рüффп
  • 5,172
  • 34
  • 67
  • 113
  • 1
    'I do not want the table itself to be changed.' How you mean 'changed?' – Roko C. Buljan Jun 28 '11 at 15:59
  • I mean changed by the wrap element (html in that case). And yes i saw that html().wrap did not work, but I mean I want to wrap the html code of the table (from to
    ).
    – рüффп Jun 28 '11 at 16:09

5 Answers5

4

You could take a copy of the table first:

$('#mytable').clone()...

To get the actual HTML of the tag you'd need something like this plugin which I posted in another answer yesterday:

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

So you can then do:

alert('<html>' + $('#myTable').outerhtml() + '</html>');

See http://jsfiddle.net/alnitak/2y988/ for a working demo.

Community
  • 1
  • 1
Alnitak
  • 334,560
  • 70
  • 407
  • 495
2

This does not work. .html() returns a string, not a jQuery object. So you cannot call wrap on it.

The other problem is that .html() only returns the inner HTML, it does not include the table tag.

You could .clone() the node, attach it to some dummy element and return the .html():

var html = ['<html><body>', 
            $('<div/>').append($('#mytable').clone()).html(), 
            '</body></html>'].join('');
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Ok, it does the trick, but finally i think the clone() function is not necessary as #mytable is not modified by this operation. – рüффп Jun 29 '11 at 07:17
  • 1
    @ruffp: If you call `.append` then the element you pass to it will be removed from current position and added to the new one. So the table would be removed from your page if you don't clone it. – Felix Kling Jun 29 '11 at 08:09
1

Maybe this jQuery outerHTML plugin will help you. It will give you the code for the table, including the enclosing <table> tags. You can maybe do something like alert("<html>" + $("#myTable").outerHtml() + "</html>").

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
0

Why not just do the following?:

alert('<html>'+$('#mytable').html()+'</html>');
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0
$("#myTable").wrap("...");

That will wrap the table in the tag supplied to the wrap function, without altering the table itself.

For more information, see the jQuery API for the wrap function.

James Allardice
  • 164,175
  • 21
  • 332
  • 312