Published in: JavaScript
URL: http://www.mohundro.com/blog/CommentView,guid,469f80ae-968d-4d60-ab5b-62a06bf045c5.aspx
This is a little trick I came up with to add outerHTML functionality in Firefox. For those who aren't familiar with outerHTML, it is an IE addition to the DOM that will return the element's HTML PLUS it's innerHTML. Is it really needed? No, but it can help with debugging sometimes.
if (document.body.__defineGetter__) { if (HTMLElement) { var element = HTMLElement.prototype; if (element.__defineGetter__) { element.__defineGetter__("outerHTML", function () { var parent = this.parentNode; var el = document.createElement(parent.tagName); el.appendChild(this); var shtml = el.innerHTML; parent.appendChild(this); return shtml; } ); } } }
Comments
Subscribe to comments
You need to login to post a comment.

This is absolutely needed! and brilliant!
And your sample almost works too, but for some reason what is actually returned in my FF browser is: try to move the mouse over me.
note the extra style="" added.
I'm using it in a function:
function getOuter(ele) { var parent = ele.parentNode; var el = document.createElement(parent.tagName); el.appendChild(ele); var shtml = el.innerHTML; parent.appendChild(ele); return shtml; }
have tried cloneNode and importNode but they don't seem to solve - any ideas? el.appendChild(ele.cloneNode(true)); var nn = document.importNode(ele, true);
cheers
second attempt at posting the extra style:
try to move the mouse over me.
sheesh third attempt, I guess [sometimes] the code has to be escaped..
<span id="try" mycolor="blue">try to move the mouse over me.</span><br />
oh dear, never mind i sussed that problem, your sample works fine in my case too -- I had an event adding then removing style elements on the fly hence leaving it with style="" in FF. IE doesn't exhibt the same behaviour so I didn't pick it up immediately. grrr! cheers
This will enable .outerHTML as a setter in Firefox: (though it will only work if you replace an element with another single element - you can't replace one with many. this code will simply ignore anything but the first element present in the HTML/XML you pass to it.)
Response to Tyson: As you point out, your defineSetter function will only parse out the first node of the passed code (and alternate attempts to remove the break command and rely on multiple this.parentNode.insertBefore(e.childNodes[i], this); calls results in an irregular every-other-node pattern. I've seen a variety of other approaches on the web that generally fall appart when confronted with self-closing tags (like input,img, etc).
I think I've got a solution that may work in all solutions (at least it's handled every test I've managed to come up with):
Anyway, between the original post and this I think that it should perfectly replicate outerHTML as used by other browsers.