bumperbox
bumperbox

Reputation: 10214

How to chain .html() in jquery

I have this snippet of code which grabs the html inside tfoot of my table (a tr) and stores it so I can use it as a template, then removes it.

   $teamTfoot = $teamsTable.find('tfoot');
    tpl = $teamTfoot.html();
    $teamTfoot.html('');

I thought I would have been able to do a one liner like this, but obviously that doesn't work.

    tpl = $teamsTable.find('tfoot').html().html('');

Is what I have done the best/easiest approach to extracting the html?

Upvotes: 0

Views: 270

Answers (2)

Ram
Ram

Reputation: 144709

As you are using .html() as a getter you can't chain it, if you want to store the value in a variable and set the html content to an empty string you can use html()'s callback function.

$teamsTable.find('tfoot').html(function(_, htmlContent) {
    tpl = htmlContent;
    return '';  
}); // .foo().bar();

Upvotes: 2

Guffa
Guffa

Reputation: 700622

Yes, what you have already is as good as it gets.

It's possible to chain commands to get the result, but then you have to store the content somewhere else while you empty the element, so that you can return it at the end:

tpl = $teamTfoot.data('tpl', $teamTfoot.html()).empty().data('tpl');

Upvotes: 1

Related Questions