3

I've got some html in a string and I need to extract a table from it. So, for example, my htmlString variable contains (:

<html><head>....some head stuff</head><body><table>.... some table stuff</table>.... other body stuff</body></html>

So, what I have tried is the following: (typed, not copied, so there may be typos)

var table = $( '' ).append( htmlString ).find( 'table' ).get();

If I view my table variable, I do see:

[<table>...</table>]

so, I believe I am extracting the table from the html string correctly.

Now, to convert this back to a string, I do the following:

var tableString = $( table[0] ).html();

and I get back:

<tbody> ... the table stuff ... </tbody>

but, what I want is:

<table> ... the table stuff ... </table>

How can I do this?

ericg
  • 8,413
  • 9
  • 43
  • 77

3 Answers3

3

jQuery doesn't have an easy way to get an element's "outerHTML". Instead of

var tableString = $( table[0] ).html();

you can do

var tableString = $(table[0]).clone().wrap('<div>').parent().html();

or, if you're not worried about compatibility with really old browsers:

var tableString = $(table[0])[0].outerHTML;
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
0

You can try this -

$( table[0] )[0].outerHTML
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0

Pure JavaScript version: http://jsfiddle.net/Zahmu/

var html = "<div><table><tbody></tbody></table></div>";

var wrapper = document.createElement("div");
wrapper.innerHTML = html;

var table = wrapper.getElementsByTagName("table")[0];
alert(table.outerHTML);

jQuery isn't giving you much in this case. You might benefit from using it locate the table element with a more complex source string, but the crux of the solution is outerHTML.

Tim M.
  • 53,671
  • 14
  • 120
  • 163