1

I have a table where the cell content is editable. Now I want, after I finished editing the table, the html code from the table with all values.

Here is a table:

<table class="table table-bordered content">
        <thead>
        <tr>
            <th>bla</th>
            <th>bla bla</th>
            <th>bla bla bla </th>
            <th>more bla</th>
        </tr>
        </thead>
        <tbody>
        <tr contenteditable="true">
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr contenteditable="true">
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        </tbody>
    </table>

<button id="save">Save</button>

That's my JS code:

    $('#save').on('click', function () {
        var table = $('.content').html();
        alert(table);
    });

The problem is that if I console.log the table variable I get this output:

  <thead>
        <tr>
            <th>bla</th>
            <th>bla bla</th>
            <th>bla bla bla </th>
            <th>more bla</th>
        </tr>
        </thead>
        <tbody>
        <tr contenteditable="true">
            <td>dwad</td>
            <td>dwada</td>
            <td>dawdaw</td>
            <td>dawdaw</td>
        </tr>
        <tr contenteditable="true">
            <td>daw<br></td>
            <td>daw<br></td>
            <td>dwadaw<br></td>
            <td>daw<br></td>
        </tr>
        </tbody>

If you have a closer look you can see that the

<table class=" ... "> and the </table> tag are gone but I also need them. Does someone know what I can do to also get the table-tags ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
WellNo
  • 649
  • 3
  • 13
  • 36
  • 2
    Possible duplicate of [Get selected element's outer HTML](http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html) – Phil Ross Apr 18 '17 at 09:38

5 Answers5

2

Try this:

var table = $('.content')[0].outerHTML;
alert(table);

Should work in every browser

myxobek
  • 445
  • 3
  • 10
1

Use Element.outerHTML

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.

$('#save').on('click', function () {
    var table = $('.content');
    alert(table.get(0).outerHTML);
});
Rayon
  • 36,219
  • 4
  • 49
  • 76
1

Use outerHTML on the node element. Like this:

$('#save').on('click', function () {
    var table = $('.content')[0].outerHTML;
    alert(table);
});
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1

Use outerHTML

$('.content').get(0).outerHTML

Check the example on JSfidle

Himanshu dua
  • 2,496
  • 1
  • 20
  • 27
1
 $('#save').on('click', function () {
        var table = $('.content')[0].html();
        alert(table);
 });

This should work.