Search code examples
jqueryhtmlcode-generationinnerhtml

Store generated HTML in variable


I have a simple jQuery table editor, and want to be able to store the whole table in a variable. Later the state of the table will be saved, sort of a mini CMS.

I tried using HTML, but it doesn't work for the generated elements.

What is the best way to to do this? Also, is what .html() returns safe, or should I not use it because of browser differences in innerHTML?

$("#target").click(function() {
    $('#myTable tr:last').after('<tr><td>Bla</td><td><div class="remove">REMOVE</div></td></tr>');
});

$("#myTable").on('click', '.remove', function(event) {
    $(this).parent().parent().remove();
});

var table = $("#myTable").html();
$("button").click(function() {
    $(".result").html(table);
});

Solution

  • Try updating the click handler to the following:

    $("button").click(function() {
        var table = $("#myTable").html();
        $(".result").html(table);
    });
    

    See it working here: http://jsbin.com/ucopun/11