views:

229

answers:

4

How to use outerHTML in JavaScript? Thanks

A: 

The outerHTML is the HTML of an element including the element itself. Contrast this with the innerHTML of the element, which is the HTML contained within an elements opening and closing tags. By definition, elements without both opening and closing tags do not have innerHTML.

Use the outerHTML when you want to completely replace an element and its contents. Use innerHTML when you only want to replace the contents of the element.

tvanfosson
+2  A: 

outerHTML is a non-standard Internet Explorer property of an element. It returns the the html of the element and its child elements. It certain cases it can be set to completely replace an element with an html string.

Phil Ross
A: 

Maybe look at jQuery and its prepend() and append() functions.

http://api.jquery.com/append/

http://api.jquery.com/prepend/

Should work in all browsers.

Also, this plugin:

http://yelotofu.com/2008/08/jquery-outerhtml/

That should cover getting and setting.

http://api.jquery.com/html/

Will get you contents within an element.

Kevin
+1  A: 
function getHTML(who){
 if(!who || !who.tagName) return '';
 if(who.outerHTML) return who.outerHTML;
 var txt, el= document.createElement("div");
 el.appendChild(who.cloneNode(true));
 txt= el.innerHTML;

 el= null;
 return txt;
}
kennebec
Interesting idea. However since most browsers that don't support outerHTML do support prototyping on HTMLElement I wonder if it would be easier to implement it pseudo-natively?
scunliffe