This is a really quick post, just thought it was useful enough to post.

There are times with jQuery where I find myself needing to get the html of an entire item.

For example…

    // somehtml.html
<div class="whatever">I want more than this html</div>

// somejs.js
// Gives me only "I want more than this html", but I want more...
$('.whatever').html(); 

Use the following quick function and you’ll have a string representing not only the innerHTML, but also the html of the actual selected element(s).

jQuery.fn.toHtmlString = function () {
    return $('<div></div>').html($(this).clone()).html();
};
// Now I have"<div class="whatever">I want more than this html</div>"...
$('.whatever').toHtmlString();

Espresso tip of the day!

Tagged with:  
  • Anonymous

    Yeah, I’ve run into the same need before too and I’ve written code very similar to what you have above. Very handy.

    If you wanted to make the API similar to .html() you could change it just a tad to something like…

    jQuery.fn.toHtmlString = function () {
    return this.length ?
    $( “” ).html( $( this ).eq( 0 ).clone() ).html() :
    null;
    };

    … so that if there is more than 1 item in the internal collection that it would only return the 1st item’s outerHTML and if there was no items it would return null like .html() does

    http://jsbin.com/3/ukarid/edit?html,javascript,live

  • for regs

    There is outerHTML property in the original DOM object. you can us it like this:

    $(‘.whatever’).get()[0].outerHTML

    or

    jQuery.fn.toHtmlString = function () {
    return $(this).get()[0].outerHTML;
    };

    • Anonymous

      Firefox was late in the game in supporting that property. It didn’t come until version 11. All other browsers had the property for quite some time. Jonathan’s technique above works for older versions of Firefox as well. You could polyfill Firefox to fix the outerHTML property or use Jonathan’s technique. https://developer.mozilla.org/en/DOM/element.outerHTML

  • http://twitter.com/pintofeggs Alex Thomas

    Very useful, thanks!

  • http://twitter.com/ajthomascouk Alex Thomas

    Very useful, thanks, i’ve needed this in the past and used some hacky code, this is much cleaner!