Here is the method I've used for this:
$.fn.outerHtml = function()
{
if (this.length)
{
var div = $('<div style="display:none"></div>');
var clone =
$(this[0].cloneNode(false)).html(this.html()).appendTo(div);
var outer = div.html();
div.remove();
return outer;
}
else
return null;
};
The basic idea is to create a hidden div and then append a clone of the
element. This uses the cloneNode method which is supported on the DOM
element by all major browers:
http://www.quirksmode.org/dom/w3c_core.htmlcloneNode(false) is used to perform a shallow clone -- there is no need to
dela with events and other similar properties.
This is followed by setting the innerHTML of the clone (since we didn't do a
deep clone).
Finally, get the innerHTML of the outer div, then remove it.
This doesn't disturb the page layout and gets your total HTML.
JK
-----Original Message-----
From:
jquery-en@googlegroups.com [mailto:jquery-en@googlegroups.com] On
Behalf Of Donald @ White Whale
Sent: Friday, December 14, 2007 2:21 PM
To: jQuery (English)
Subject: [jQuery] Getting .html() AND the container element
(Apologies of this double-posts somehow; lots of trouble with Google
Groups earlier, haven't seen the message come up yet, so:)
For an Ajax application I'm working on, I need to POST the HTML
contents of an element including the element itself. So if I have
<div class="example" id="example10">
Lorem ipsum <strong>dolor sit amet</strong>.
</div>
I need to grab that entire bit as a single string, including the first
div and it's attributes.
The only way I can figure to do this is to .wrap() the entire element
in another div, then get the .html() of that wrapper, then remove the
wrapper. This feels clumsy and inefficient for a pretty
straightforward task, and messes with the DOM a bit more than I'd like
(the changes can theoretically mess with the page layout on the
viewer's end). Is there a better way to do this?