JavaScript
Article

jQuery Get html Including Element Tag

By Sam Deering

Incase you are using a lot of ajax functionality (I know I am) it might be useful to grab an elements html including the tag. I’m sure there must be an easier way than just cloning the element in a wrapper and then grabbing the wrapper html using jQuery to get the inner html including element tag html.

Until I find a better (more efficient way) here is the code snippet.

.clone().wrap('
').parent().html();

Some other ways (from post comments, thanks guys):

//Not sure how portable it is across browsers
$(‘#foo’)[0].outerHTML;
var foo = $(‘#bar’);
var foo = $('h1');

console.log(foo);
//output: jQuery(h1) < - DOM Element

console.dir(foo[0]);
//output: DOM element props and funcs

console.log(foo[0]['outerHTML']);
//output: 

Title

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • http://www.warpdesign.fr warpdesign

    There is a faster way: $(‘#foo’)[0].outerHTML

    Not sure how portable it is across browsers though…

  • IdemIsDito

    var foo = $(‘#bar’);

    the foo variable will be the element including the outer tag element.

    • jquery4u

      @IdemlsDito, thanks, this seems to work better?

      var foo = $(‘h1’);

      console.log(foo);
      //output: jQuery(h1) < - DOM Element console.dir(foo[0]); //output: DOM element props and funcs console.log(foo[0]['outerHTML']); //output:

      Title

    • starrychloe

      Yes, but it’s not a String! You cannot use String functions on it!

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.