jQuery OuterHTML

Applies To: jQuery 1.0+

Often in debugging I’d like to pull back the full HTML for an object and take a look at it. The html() method is great for a lot of things, but it’s limited to just the inner HTML and often doesn’t contain the stuff I’m looking for. So here’s a helper function I wrote that gives you back the full HTML as a string:

function fullHTML(jQueryElem) {
	var fullH = jQueryElem.wrap('<div>').parent().html();
	jQueryElem.unwrap();
	return fullH;
}

All it does is perform a temporary wrap around whatever jQuery Element you pass in, grab it’s parent (which is now the Div we just wrapped it in) and grab the parent’s inner HTML (which is of course the full HTML of our object). Then we just unwrap it in line 3 and return the string in line 4.

You can call it like this (this code just writes it out to the console):

console.log(fullHTML($('#myobjectID')));

It’s quick and easy and I use it in development all the time. Hopefully it helps you too.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s