0

I have a table and I would like to assign the HTML as a string variable. How can I do it so that the opening/closing table tags are included in the string? I know I could just wrap the table in a container and get the HTML of the container, but wondering if there's a solution without modifying the layout.

$(function() {
  // want the following variable to include open/closing table tags
  var tableHTML = $('table').html();
  
  alert(tableHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</table>
user13286
  • 2,822
  • 8
  • 40
  • 83
  • You can use clone() method to achieve that. Also pure javascript provide a method of any container dom object dom.outerHTML which method will return html including target element. – Hanif Nov 01 '17 at 17:43

2 Answers2

1

Using outerHTML

$(function() {
  // want the following variable to include open/closing table tags
  var tableHTML = $('table')[0].outerHTML;

  console.log(tableHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</table>
bhansa
  • 6,780
  • 2
  • 27
  • 49
1

Try this.

$(function() {
  // want the following variable to include open/closing table tags
  var tableHTML = $('table').prop('outerHTML')
  
  alert(tableHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</table>
Muhammad Usman
  • 9,766
  • 21
  • 39