How to get the outerHTML of an element using jQuery
At the time of this writing, jQuery does not have a function to get the outerHTML of an element on a web page. But that’s ok, since we can accomplish this with just a few function calls strung together.
Some Sample HTML
Let’s take a look at some HTML.
<div id="container"> <p> I am some text inside a 'p' tag. <span>I am a child element in this paragraph.</span> </p> <span>I am some text inside a 'span' tag.</span> <input type="text" name="someinput" value="I am a value inside an input tag." /> </div>
Getting HTML From An Element (inner HTML, that is)
Let’s say we wanted to get the HTML contents of the “container” div element. We could use jQuery’s html() method. But, what if we wanted to get the outer HTML of that element? If the element had no siblings then it would be safe to use the jQuery parent() method like so:
var htmlString = $('#container').parent().html();
The problem is that the parent element might have other children, and we don’t want to include all their HTML too. And so, here is the long story (one story anyway) of how to get the outer HTML with jQuery.
jQuery outerHTML: Step One
We would first want to create a jQuery object for our target element, having an ID of “container”.
var $target = $('#container");
jQuery outerHTML: Step Two
Next it would be wise to create a copy, or clone, of the element object. That way we don’t risk doing anything on accident to the source element.
var $clone = $target.clone();
jQuery outerHTML: Step Three
Now this line of code is really the point of this example. We will wrap our clone element with a dummy element. This gives it a parent with no other children. Maybe you see where we’re going with this. Note that the parent type isn’t restricted to a div, like I have chosen here, but it’s probably best to chose something without any real special function. Using ‘p’, ‘span’, or even your own ‘xyz’ should all be safe.
jQuery outerHTML: Step Four
The last part is to call the jQuery html() function on the dummy parent object.
var htmlString = $clone.parent().html();
Mission Accomplished. Yay!
There you have it! One really long explanation of how to do something that could be real simple, like referencing outerHTML on the DOM object. But, I’m a jQuery fanatic, and for good reason. This just happens to be one function that jQuery hasn’t created yet.
Try It Yourself
Here is the source code of a complete working test.
One Simple Line Of Code
Here is that simple line of code I promised:
var htmlString = $('#targetElementId').clone().wrap('<div>').parent().html();