JavaScript
Article
By Sam Deering

jQuery Get html Including Element Tag

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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):

--ADVERTISEMENT--

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

console.log(foo);
//output: jQuery(h1) Title
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?