How to return the result without changing the source?

My HTML and JavaScript code is as follows:

<html> <!--... many code ...--> <button onclick="alert($('#mytable').html().wrap('<html/>') );">Show HTML Table</button> <table id="myTable"> <tr and td's> </table> <!--... many code ...--> </html> 

I want my javascript to return a table wrapped with HTML tags, but I don't want the table itself to change.

+1
source share
5 answers

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

Another problem is that .html() returns only internal HTML, it does not include the table tag.

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

 var html = ['<html><body>', $('<div/>').append($('#mytable').clone()).html(), '</body></html>'].join(''); 
+3
source

First you can take a copy of the table:

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

To get the actual HTML tag, you 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:

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

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

+4
source

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

+1
source

Why not just do the following?

 alert('<html>'+$('#mytable').html()+'</html>'); 
0
source
 $("#myTable").wrap("..."); 

This will transfer the table to the tag provided by the wrap function without changing the table itself.

See the jQuery API for the wrap function for more information.

0
source

Source: https://habr.com/ru/post/1387359/


All Articles