Store generated HTML in variable

23,744

Solution 1

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

Solution 2

Do you want to store the whole table in a different element or in a variable ?

If you want to store it in a variable then

$('button').on('click', function(){
    var table_html = '<table id="myTable">' + $('#myTable').html() + '</table>';
    // alert(table_html);
});

Fiddle - http://jsfiddle.net/84ETb/

Solution 3

Can't you just call html() after you've done your modifications (i.e. when the button is clicked, not when the DOM is ready)

var the_content = $('#myTable').html();
Share:
23,744
user1721135
Author by

user1721135

Updated on December 11, 2020

Comments

  • user1721135
    user1721135 over 3 years

    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);
    });
    
  • user1721135
    user1721135 over 11 years
    i did, but this doesnt get the generated html, see my fiddle jsbin.com/ucopun/9
  • Dennis Martinez
    Dennis Martinez over 11 years
    @user1721135 You will have to bump up to the parent and then grab the html from the parent. $('#myTable').parent().html();
  • BenM
    BenM over 11 years
    You're not calling .html() when the button is clicked, but rather when the document loads. Move your line into the button click, and it works as you wish: jsbin.com/ucopun/10
  • BenM
    BenM over 11 years
    No they weren't... look at the times of the posts. The accepted answer was posted 5 minutes after mine...