Quantcast
Viewing all articles
Browse latest Browse all 12

Espresso Tip: Get an element’s entire Html string with jQuery

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!


Viewing all articles
Browse latest Browse all 12

Trending Articles